Docker compose is a tool used to define and run multi-containers for Docker applications. With compose you use a YAML file to configure services for your application. Then use the command to create and run from those configs. Using is also quite simple with just three steps:
Declare the app's environment in Dockerfile.
Declare the necessary services to run the application in the docker-compose.yml file.
Run docker-compose up to start and run the app.
Characteristic
Unlike Dockerfile (build images). Docker compose is used to build and run containers. The operations of docker-compose are similar to the command: docker run.
Docker compose allows creation of many similar services (containers) with the command:
FROM node:carbon-alpine AS node_builder
WORKDIR /app/webreactjs
COPY /webreactjs/package.json .
RUN npm install
COPY /webreactjs .
LABEL name="webreactjs" version="1.0"
EXPOSE 3000
CMD ["npm", "start"]
FROM golang:1.11 AS go_builder
ADD . /app
WORKDIR /app
RUN go mod download
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-w" -a -o /main .
LABEL name="server" version="1.0"
FROM alpine:latest
RUN apk --no-cache add ca-certificates
COPY --from=go_builder /main ./
RUN chmod +x ./main
EXPOSE 8080
CMD ./main
Proceed to build Dockerfile
Config services need to be started and run in the docker-compose.yml file
version : indicates the version of docker-compose used.
services : set up the services(containers) you want to install and run.
image : Indicates the image used while creating the container.
build : used to create containers.
ports : set up running ports on the host machine and in the container.
restart : automatically launched when the container is shut down.
There are also some other config commands:
environment : sets environment variables (usually used while configuring database parameters).
depends_on : indicates the dependency. That is, any service must be installed and run first before the service configured there can run.
volumes : used to mount two directories on the host and container together.
Run command as below:
$ docker-compose up
After running, we see that docker-compose has started and run the two services we configured in the docker-compose.yml file above.
Now it's time for us to admire the results
Pro tip : For those of you who use Visual Studio Code like me, you can quickly create configs for Dockerfile and docker-compose.yml with just a few small steps. On Visual Studio Code, you install the Docker extension
After installation, press F1 => type docker: add => select available temp + config port. Visual Studio Code will automatically generate the files Dockerfile, docker-compose.yml, docker-compose.debug.yml, and.dockerignore for you.
Config in Dockerfile. If you do not know about the commands to configure Dockerfile. Don't worry, watch part 1 again: