Docker-Compose Introduction

by

So today we'll take a look at dipping our toes into docker-compose.

What is docker compose?

docker-compose is a tool for defining, running, and managing multiple containers at once. It's very useful for development environments and home servers, where you want many services running in parallel on one machine.

Downloading docker-compose

You can often download docker-compose through your distribution's package manager. If it's not, you can easily download it with pip:

Docker-compose

pip3 install docker-compose

Podman-compose

pip3 install podman-compose

Now for the juicy part

Start by creating a directory where you want your configuration to be stored, and create a docker compose file:

mkdir docker-compose-tutorialcd docker-compose-tutorialvim docker-compose.yml

Every docker-compose file needs to start with an API version, we'll use api version 3

version: '3'

Next we'll define a service, so go ahead and create a services entry and follow up with a service name:

version: '3'services:    my_service:        

Now, under the service name you can start adding attributes.

version: '3'services:    my_service:        image: httpd        ports:            - 8080:80

This configuration defines a service "my_service" that spawns a container with an httpd image, and binds the container's port 80 to our local machine's port 8080.

Now run the docker-compose file with

docker-compose up

Open up a browser and visit 127.0.0.1:8080

You should see a success page, now let's see how we can change the container's index.html file to our own file.

make a new folder called html and create inside it a file called index.html with the page you want to serve:

mkdir htmlcd htmlecho "

Hello World!

" > index.html

Now go back to your docker-compose file, and add the following under my_service below where you put the ports definition:

version: '3'services:    my_service:        image: httpd        ports:            - 8080:80        volumes:            - ./html:/usr/local/apache2/htdocs/

What this means is that we will mount the content of the directory html relative to the docker-compose file inside /usr/local/apache2/htdocs.

Restart your container(s) with the folowing command:

docker-compose restart

Visit your browser again and reload the page, you should see the html file being served by your container.

Passing environment variables to your service

A common thing to want to do, besides choosing an image and mounting folders is to pass environment variables to your services. Here is an example for doing so:

version: '3'services:    my_service:        image: httpd        ports:            - 8080:80        volumes:            - ./html:/usr/local/apache2/htdocs/        environment:            - FOO=bar            - SPAM=eggs