Docker Compose

Page content

Concept

Docker Compose enable us to manage multi container environments in a file.

Install

  • As of Dec.2021
  • On Ubuntu 20.04
  • V2

https://docs.docker.com/compose/cli-command/#install-on-linux

$ mkdir -p ~/.docker/cli-plugins/
$ curl -SL https://github.com/docker/compose/releases/download/v2.0.1/docker-compose-linux-x86_64 -o ~/.docker/cli-plugins/docker-compose
$ chmod +x ~/.docker/cli-plugins/docker-compose
$ docker compose version
Docker Compose version v2.0.1

Sample: php-fpm with Nginx

Directory structure

$ tree
.
├── README.md
├── docker-compose.yml
├── front-php
│   └── Dockerfile
└── nginx_conf
     └── front.conf

docker-compose.yml:

version: "3"
services:
  front-nginx:
    image: nginx:latest
    container_name: front-nginx
    ports:
      - "80:80"
    volumes:
      - {{ path_to_php-fpm_app }}/myconf.conf:/etc/nginx/conf.d/myconf.conf
      - {{ dir_to_webapp }}:/var/www/html
    links:
      - front-php
  front-php:
    build: front-php
    container_name: front-php
    ports:
      - "9000:9000"
    volumes:
      - {{ dir_to_webapp }}:/var/www/html

links: option links to containers in another service.

The links option is legacy, so you should move to [networks option(https://docs.docker.com/compose/compose-file/compose-file-v2/#networks)].

nginx_conf/front.conf

server {
    listen 80;
    index index.html;
    server_name mylaptop.local;
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/html/www;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass front-php:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

front-php/Dockerfile

FROM php:8.1.0-fpm
RUN docker-php-ext-install -j$(nproc) pdo
WORKDIR /usr/src
## Configure library here if you want

Now, run the containers with docker compose:

docker compose -f {{ YAML file }} up

References: