Getting Started With Docker Compose With Examples

Docker Compose is a tool for defining and running multi-container Docker applications. When usind docker, running and managing multiple containers becomes cumbersome. Docker compose solves this problem.

You use yaml to configure your application services. The yaml file is always named docker-compose.yml but you can give it a different name then specify it. Compose provides docker-compose command to manage the containers defined in the yaml file.

Also check

Installing docker-compose

You can run Compose on macOS, Windows, and 64-bit Linux

Docker Compose relies on Docker Engine, make sure you have Docker Engine installed before proceeding.

Install using pip

Use this command:

1
pip install docker-compose

WordPress Mysql example

You can use Docker Compose to easily run WordPress in an isolated environment built with Docker containers. This quick-start guide demonstrates how to use Compose to set up and run WordPress.

Sample docker-compose.yaml file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
version: "3.9"

services:
  db:
    image: mysql:8.0
    volumes:
      - ~/apps/wordpress/db:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: toor
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

  wordpress:
    depends_on:
      - db
    image: wordpress:5.8.0
    volumes:
      - ~/apps/wordpress/site:/var/www/html
    ports:
      - 8000:80
    environment:
      WORDPRESS_DB_HOST: db:3306
      WORDPRESS_DB_USER: wordpress
      WORDPRESS_DB_PASSWORD: wordpress
      WORDPRESS_DB_NAME: wordpress

volumes:
  db_data: {}
  wordpress_data: {}</code></pre>

Running the project:

```sh
docker-compose up -d
1
docker-compose exec wordpress sh

Use http://localhost as the IP address, and open http://localhost:8000 in a web browser.

If you need to use sudo to bring up containers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
version: "3.9"

services:
  db:
    image: mysql:8.0
    volumes:
      - ~/apps/wordpress/db:/var/lib/mysql
    privileged: true
    user: root
    environment:
      MYSQL_ROOT_PASSWORD: toor
      MYSQL_DATABASE: wordpress
      MYSQL_USER: wordpress
      MYSQL_PASSWORD: wordpress

Shutdown and cleanup

The command docker-compose down removes the containers and default network, but preserves your WordPress database.

The command docker-compose down volumes removes the containers, default network, and the WordPress database.

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy