Cookie Consent by TermsFeed

Docker-ize your Services - Part 3 - docker-compose

Docker-ize your Services - Part 3 - docker-compose

One of the most interesting tools you should be learning about is the docker-compose tool.

docker-compose allows you to define a set of containers in a single file. They will be in their “namespace” and can be linked and tied together. It’s useful both for development and for single host deployment because you can define all the containers you need for a specific project and keep them running in a consistent way.

So let’s consider, for example, a set of containers. We need an apache/php container, linked to a mysql db container. More, we need phpmyadmin to initialize and populate the database.

Let’s start creating a directory called “webroot” and, inside, a index.php file:


<title>PHP test</title>

echo "Hello, World!";

Now that we have the apache root directory, we can continue creating a docker-compose.yml file:

version: '3'

    image: mysql:5.7
      MYSQL_DATABASE: test_db
      MYSQL_USER: testuser
      MYSQL_PASSWORD: testpass
    restart: unless-stopped
    image: php:7.4-apache
    container_name: php_web
      - db
      - ./webroot/:/var/www/html/
      - "9000:80"
    restart: unless-stopped
      - db
    image: phpmyadmin/phpmyadmin
    restart: unless-stopped
      - '8080:80'
      PMA_HOST: db

This file will describe three containers. The first is the db and we will pass some options (like passwords, etc) as environment variables. It’s not the best way to do it, but it’ll be ok for now. We will also ask the containers to restart unless manually stopped, for example after a reboot.

Then we will create a apache/php container and will pass the webroot/ as its html directory. We will tell this container that it will need the “db” container, so db is needed and must be running in order to launch the web container. We will also ask this container to map the host port 9000 to its port 80.

At last we have the phpmyadmin container. It will depend from the db container and we will say that the host to be considered as db host is “db”, which can be used inside the same docker-compose.

Please note: all those containers will be in a specific space, so they can call each other by name but can’t be called just as “db” from other containers, outside the docker-compose.

Now we can use the command “docker-compose up” and we will see the db container going up, then the web and phpmyadmin. We can connect to host port 9000 and see the “Hello world” php page, to host port 8080 and we will reach phpmyadmin.

docker-compose is a powerful tool, so I suggest to study the official documentation.

See also