Docker Compose

What is Docker compose?

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:

Demo

Website setup :

npm

or yarn

The demo is React js web

Change the App.js file

App.css

Server part :

main.go

Config in Dockerfile. If you do not know about the commands to configure Dockerfile. Don't worry, watch part 1 again: here

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:

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

Web : Run at: http://localhost:3000

Server : Runs at: http://localhost:8080

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.

Last updated