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:

webroot/index.php

<html>
<head>
<title>PHP test</title>
</head>

<body>
<?php
echo "Hello, World!";
?>
</body>
</html>

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

version: '3'

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

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