Sometimes, we want to use docker-compose to build multiple services.
In this article, we’ll look at how to use docker-compose to build multiple services.
How to use docker-compose to build multiple services?
To use docker-compose to build multiple services, we can create a Dockerfile for each service.
Then we create a docker-compose.yml to build each service with the Dockerfile for each service.
For instance, if we have the frontend and backend service in the frontend and backend folder respectively, then we create a docker-compose.yml in the root folder with
version: "3"
services:
frontend:
build: ./frontend
ports:
- "8091:8091"
backend:
build: ./backend
ports:
- "8090:8090"
volumes:
- ./backend:/usr/src/app
We set build to the folder with the Dockerfile we want to run.
ports map the port from the Docker container to the port exposed to the outside.
volumes map the folder in the project to the folder in the Docker container.
In the frontend folder, we add a Dockerfile by writing
FROM node:lts-alpine
RUN npm install -g http-server
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 8091
CMD [ "http-server", "dist", "-p 8091"]
to build the frontend container.
And in the backend folder, we add a Dockerfile by writing
FROM node:16
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
RUN npm i -g nodemon
COPY . .
EXPOSE 8090
CMD [ "nodemon", "-L", "server.js" ]
to build the backend container.
And then we run docker-compose up to build both containers.
Conclusion
To use docker-compose to build multiple services, we can create a Dockerfile for each service.
Then we create a docker-compose.yml to build each service with the Dockerfile for each service.