Get started with Docker Compose
Docker Compose is a tool that simplifies work with multiple containers. In the previous article we have shown how to create a simple Docker image and how to run a Docker container with only using Dockerfile. In this article we will create the same image but with using docker-compose.
If you haven't installed docker-compose tool yet, you can install it by following the official instructions.
After successful installation you should have the docker-compose command available in your console.
Creating the docker-compose.yml
In the same directory where you have the Dockerfile (created in the previous article) create another file called docker-compose.yml and add the following line inside.
This instruction says to use the third version of the Compose file format.
To define the same container as we have in the Dockerfile we need to create a services section with the hello-world section including its configuration. Unlike the previous article, we will try php:apache image instead of the pure PHP image.
version: '3' services: hello-world: container_name: 'hello-world-test' image: php:apache ports: - '80:80' volumes: - './:/var/www/html'
Now a bit of explanation what does those parameters means:
- hello-world - is the service name in the docker-compose file
- container_name - sets the container name to hello-world-test (it is the same as --name parameter when running docker run ... command)
- image - is the name of the php image we are going to use
- ports - allows us to define the external and internal ports where the first number is the external port and the second is the internal port. It is also possible to set multiple ports
- volumes - in a nutshell there are paths for shared directories between your computer or server and Docker Container. Volumes can be modified by using flags that can improve the performance of mounted volumes
Building the Image
Do you remember the command for building the image from the first article? It is in fact a very short and simple command but using docker-compose it can be even more simple. Just move the cli into the directory with the docker-compose.yml file and run
That's all. Simple, right?
Running the Container
Running container with docker-compose is very simple. Just run
To check, whether the container is running you can use the following command which shows you all running containers defined in docker-compose.yml file.
Now, when you open your browser and type http://localhost you should be able to see the Hello World! text.
For stopping the container use the following command
docker-compose stop hello-world
(hello-world is the name of the service you want to stop; if want to stop all services, just don't add any).
The container defined in docker-compose.yml can be removed by this command (the -f parameter will skip the confirmation question).
docker-compose rm -f