Skip to content
ImagineWorld

Network and Volumes Fundamentals

node_idnode-book_a-developer-s-essential-guide-to-docker-compose_chapter-03-network-and-volumes-fundamentals
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleNetwork and Volumes Fundamentals
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Network and Volumes Fundamentals

Section titled “Chapter 3 — Network and Volumes Fundamentals”

In the previous chapter, we managed to create our core Go application and provide storage using a Redis server. By having our core application in place, we proceeded to more advanced Docker concepts such as health checks, building images, tagging, and logically grouping using labels. The usage of volumes and networking was present throughout the chapter. Networking and volumes were being used all along; however, it was done transparently. This chapter will focus extensively on networks and volumes and how to configure them on a Compose-based application.

The first part will focus on volumes, how volumes map to Compose, how they work behind the scenes, and how to use them. Volumes play a crucial role in Docker. They allow you to attach external documentation and files that are needed for an application. Volumes can be shared and used to help with operations in an application.

The second part will focus on networks. Docker provides networking simply and transparently. In special scenarios, various options exist that can ensure multi-host communication, a different layer of networks between applications, and better isolation between containers.

In this chapter, we will cover the following main topics:

  • Explaining Docker volumes
  • Attaching a Docker volume to a container
  • Docker volume drivers
  • Declaring Docker volumes on Compose files
  • Attaching a Docker volume to an existing application
  • Creating a configuration file
  • Mounting a file using volume
  • Docker networking
  • Defining networks on a Compose configuration
  • Adding an extra network to the current application

The code for the book is hosted on GitHub at https://github.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose. In case of an update to the code, it will be updated on GitHub.

When developing an application, a crucial aspect is to utilize operations that interact with a filesystem. Those operations can be driven by data storage purposes or, in some cases, might be configuration-driven. For example, take a database application that needs a filesystem to operate and store data. The same also applies to configurations that apply to an application. Let’s imagine a JEE application that is heavy on XML configuration. It needs to be able to read and store data inside a filesystem. The issue with disk operations on a Docker container is that once the container is shut down, all of the changes will be lost. In this case, Docker provides us with volumes. Volumes are the preferred mechanism for persisting data that is generated and used by a container.

Here is a list of some of the characteristics of volumes:

  • Volumes and their data can remain after a container has been deleted.
  • A volume can be attached to another container.
  • Volumes can be used by more than one container simultaneously.
  • Volumes are abstract.
  • Volumes can be local or remote.

Now that we have an overview of what volumes can provide, in the next section, we will proceed with adding volumes to containers and interacting with them.

We will create our first Docker volume using the following:

$ docker volume create example-volume
example-volume

We will inspect the volume that we’ve just created:

$ docker volume ls --filter="name=example-volume" --format='{{json .}}'
{"Driver":"local","Labels":"","Links":"N/A","Mountpoint":"/var/lib/docker/volumes/example-volume/_data","Name":"example-volume","Scope":"local","Size":"N/A"}

By inspecting the preceding volume, we see that the volume is using the local driver. A local driver is the default driver option when creating volumes. The volume data will reside on the host that Docker Engine runs. There’s also a mount point to our local filesystem. This is where the data in this volume resides physically on the host.

Since we created the volume, we will put it to use with a container. We will attach the volume and write some data on it. We can do this by mounting the volume to the container using --mount:

$ docker run -it --rm --name example-volume-container --mount source=example-volume,target=/storage bash
bash-5.1# echo some-text > /storage/data-file.txt
bash-5.1# cat /storage/data-file.txt
some-text
bash-5.1# exit

Let’s break down what has been executed into steps:

  1. We run a bash container in interactive mode.
  2. Once we exit the container, it will be stopped and deleted.
  3. We mounted the volume at the /storage path.
  4. We created a file on that path.
  5. The file should be persisted on the volume.

We will create another container with the volume mounted and examine whether the file will be present:

$ docker run -it --rm --name second-volume-container --mount source=example-volume,target=/storage bash
bash-5.1# cat /storage/data-file.txt
some-text

As expected, the volume is mounted, and the file is there.

In another Terminal session, we will inspect the container and the Mounts section:

$ docker inspect second-volume-container --format '{{json .Mounts}}'
[{"Type":"volume","Name":"example-volume","Source":"/var/lib/docker/volumes/example-volume/_data","Destination":"/storage","Driver":"local","Mode":"z","RW":true,"Propagation":""}]

Let’s exit both Terminal sessions. As you can see, the volume has been attached and contains the volume information and the destination directory. After successfully creating a volume and attaching it to the containers, we will proceed with the scenario of a volume being shared.

Earlier, we used one volume and attached it to a container. After stopping the container and mounting the volume to another container, we navigated to the directory and found that the data stored from the previous steps was there. A useful feature is that the volume can be attached to more than one container. By running the following commands in parallel, there will be writes on the same volume simultaneously:

$ docker run -it --rm --name container-2 --mount source=example-volume,target=/storage bash -c "for i in \$(seq 1 1 100000); do echo \$HOSTNAME \$i >> /storage/\$HOSTNAME.txt ; done"
$ docker run -it --rm --name container-1 --mount source=example-volume,target=/storage bash -c "for i in \$(seq 1 1 100000); do echo \$HOSTNAME \$i >> /storage/\$HOSTNAME.txt ; done"

As expected, if we attach the volume and navigate to the directory, we should see two different files created:

$ docker run -it --rm --name container-1 --mount source=example-volume,target=/storage bash
bash-5.1# ls /storage
770bdfc4dc94.txt b9b09390cf17.txt data-file.txt

Both containers have been successful in storing files to the volume.

We were successful in using the original volume in a secondary container. There are scenarios where writes should be only executed from one container, whereas other containers could only read the data persisted by having read-only permissions.

As shown in the following example, mounting the volume as read-only prevents us from writing any files to it:

$ docker run -it --rm --name read-only-volume-container --mount source=example-volume,target=/storage,readonly bash
bash-5.1# cat /storage/data-file.txt
some-text
bash-5.1# touch /storage/test.txt
touch: /storage/test.txt: Read-only file system
bash-5.1# exit

So, we have become familiar with volumes and how to mount and use them with our containers. We also successfully mounted a volume for read-only purposes. In the next section, we will learn about volume drivers and what they can offer.

We created Docker volumes and we put them to use in our containers. By inspecting the volume in the previous example, we can get some valuable information:

$ docker volume inspect example-volume
[
{
"CreatedAt": "2022-03-08T07:01:29Z",
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/example-volume/_data",
"Name": "example-volume",
"Options": {},
"Scope": "local"
}
]

Here, "Driver" is set to "local"; this means that the volume data will reside locally in our workstation, and the driver will facilitate disk operations from the Docker container to the VM path.

We will use this as an opportunity to see the physical location of this file. In this example, which is running on macOS, we need to connect to the VM that hosts Docker Engine. We will do this using netcat:

$ nc -U ~/Library/Containers/com.docker.docker/Data/debug-shell.sock
/ # cat /var/lib/docker/volumes/example-volume/_data/data-file.txt
cat /var/lib/docker/volumes/example-volume/_data/data-file.txt
some-text
/ # exit
exit

Let’s break down what we just did. On macOS and Windows, Docker Engine runs on a VM:

  1. We need to shell to that VM and examine the directory.
  2. Once we are inside the VM, we can confirm that the data is stored there.

As we understand that a volume can be located anywhere, the driver will facilitate making the usage of the volume possible.

Volume drivers can enable interactions with a remote filesystem and persist data. Available drivers include Azure File Storage, NFS, and AWS EFS.

Apart from highlighting the feature of interacting with a volume on a remote host, a volume driver can be used to add extra functionality when storing data; for example, by adding a form of proprietary encryption in transit or storage.

Using a volume driver versus mounting locally

Section titled “Using a volume driver versus mounting locally”

Based on the contents of the last section, there are various options that we can use to interact with a remote filesystem. One option that is available and bypasses driver functionality is to mount the filesystem to the host. This way, the remote filesystem is attached to the container through the host that has already mounted it. It’s up to the user and the use case to decide what should be used. Use cases can expand from having less maintenance overhead to the customized handling that a volume driver can provide.

So far, we have created some volumes using the command line and we also looked at how volumes work behind the scenes along with ways to interact with remote files using drivers. The next section will focus on using the volume knowledge that we have acquired in a Compose application.

We’ve been able to create a Docker volume and use it, and had a look at its features. The step next is to create and use volumes using Compose. Volumes on Compose are defined in the volumes sections:

services:
nginx:
image: nginx
volumes:
example-compose-volume:

The configuration option on volumes can apply to example labels:

services:
nginx:
image: nginx
volumes:
example-compose-volume:
labels:
- com.packtpub.compose.app=volume-example

Alternatively, you can have more advanced configurations, for example, a driver that is configured to use nfs:

services:
volumes:
nfsvol:
driver_opts:
type: "nfs"
o: "addr=127.0.0.1,nolock,rw"
device: ":/data"

So, we have created and configured volumes using Compose. Now we can proceed with adapting our existing Compose application to use volumes.

Attaching Docker volumes to an existing application

Section titled “Attaching Docker volumes to an existing application”

The previous chapter was focused on a Task Manager application using a Redis database. Being a database, Redis is subject to backups and other disk operations.

Our previous Redis Compose configuration is as follows:

services:
redis:
image: redis
ports:
- 6379:6379
labels:
- com.packtpub.compose.app=task-manager

Redis has various options for persistence options (https://redis.io/topics/persistence). There are options from point-in-time to AOF (Append-Only File)-based persistence. We will focus on the point-in-time snapshot option that Redis provides, and we will use a volume to store those snapshots.

By default, .rdb backups on the Redis Docker image are stored within the /data directory. We will mount a volume to that location.

First, we will create the volume:

volumes:
redis-data:
labels:
- com.packtpub.compose.app=task-manager

Then, we will attach the volume to the container:

services:
redis:
image: redis
ports:
- 6379:6379
volumes:
- redis-data:/data

Since the volume is attached to the database, the backups are stored in the volume and can also be accessed by another container. In the following section, we will create a custom configuration for the Redis service in order to be able to increase the frequency of our backups.

Based on the documentation, we will enable Redis to take a snapshot of at least one key change in 60 seconds. Our Redis configuration will look like this:

dbfilename taskmanager.rdb
save 60 1

Here, we changed the backup name to taskmanager.rdb. We will take a snapshot every 60 seconds if at least one key changes. Now that the configuration is ready, we need a way to attach this configuration file to the database we created earlier using Compose.

The configuration file has been created and will be mounted by using bind mounts. A bind mount enables us to mount a file on the workstation running Docker Engine to the Docker container. When using Compose, bind mounts are defined in the volumes sections. This might be confusing since it’s in the same section as volumes; however, it’s a bind mount.

We will mount the Redis configuration file to the container and alter entrypoint:

services:
redis:
image: redis
ports:
- 6379:6379
entrypoint: ["redis-server","/usr/local/etc/redis/redis.conf"]
labels:
- com.packtpub.compose.app=task-manager
volumes:
- ./redis.conf:/usr/local/etc/redis/redis.conf
- redis-data:/data

By inspecting the container, we can justify that the file has been mounted using bind mount:

$ docker inspect chapter3-redis-1 --format '{{json .Mounts }}'
...
{
"Type": "bind",
"Source": "/path/to/repo/A-Developer-s-Essential-Guide-to-Docker-Compose/Chapter3/redis.conf",
"Destination": "/usr/local/etc/redis/redis.conf",
"Mode": "rw",
"RW": true,
"Propagation": "rprivate"
}
...

Since we managed to configure Redis to take point-in-time snapshots on a volume of our choice, we will proceed with creating a backup of these snapshots using another process that has read access to the original backup volume.

Now, we would like to save the snapshots created over time to a file. This way, we can restore the database from a point in time. However, we want to store the backups to another volume whose sole purpose will be for backups:

...
volumes:
- ./redis.conf:/usr/local/etc/redis/redis.conf
- redis-data:/data
volumes:
redis-data:
backup:

Another container will be introduced. The container will have the responsibility of copying the Redis backups and moving them to the backup folder. The container will not be very sophisticated; it will just be a simple bash script that will run every few seconds.

The bash script for copying the Redis backups is as follows:

#!/bin/sh
while true; do cp /data/taskmanager.rdb /backup/$(date +%s ).rdb; sleep $BACKUP_PERIOD; done

The container will run the script that has been created. Since we’ve got everything we need, let’s configure the container.

Both volumes need to be mounted. The Redis backup volume will be read-only. The responsibility of the backup process is to copy the current file on the Redis data directory and append a timestamp during the time of the backup:

redis-backup:
image: bash
entrypoint: ["/snapshot-backup.sh"]
depends_on:
- redis
environment:
- BACKUP_PERIOD=10
volumes:
- ./snapshot-backup.sh:/snapshot-backup.sh
- redis-data:/data:ro
- backup:/backup
volumes:
redis-data:
backup:

Note that we used the read-only option on data. This can also be defined alternatively:

volumes:
- type: volume
source: redis-data
target: /data
read_only: true

Our Redis database includes the snapshot backup process, as follows:

services:
...
redis-backup:
image: bash
entrypoint: ["/snapshot-backup.sh"]
depends_on:
- redis
environment:
- BACKUP_PERIOD=10
volumes:
- ./snapshot-backup.sh:/snapshot-backup.sh
- redis-data:/data:ro
- backup:/backup
labels:
- com.packtpub.compose.app=task-manager
volumes:
redis-data:
labels:
- com.packtpub.compose.app=task-manager
backup:
labels:
- com.packtpub.compose.app=task-manager

Let’s run the preceding Compose application:

$ docker compose up

Now we should be able to execute the same cURL requests we executed in Chapter 2, Running the First Application Using Compose.

So far, we’ve been able to migrate our original Redis service on Compose to use a volume. Additionally, we’ve added another service to issue a backup process by having the backup volume mounted in read-only mode and storing the backups in a backup purpose container. In the next section, we will dive into Docker networking and learn how we can apply it to Compose.

A crucial feature of Docker is its networking features. The containers running on Docker communicate and interact transparently. Thanks to the network layer, Docker provides various networking aspects that are tackled efficiently, as follows:

  • Private networks
  • Internal DNS
  • Container communication
  • Bridging containers

Let’s see the available networks that are currently running:

$ docker network ls
NETWORK ID NAME DRIVER SCOPE
6a149c758fc2 bridge bridge local
9ec7758d7050 chapter1_default bridge local
7c95e79497b6 chapter2_default bridge local
16fda3c38e57 chapter3_default bridge local
4a6d6a3e8475 host host local
be28a5cd8a16 none null local

Networks on Docker can come in various forms. The most used formats include the following:

  • Bridge
  • Host
  • Overlay

Let’s look at each of them in the following sections.

Bridge is the default network driver when using Docker. A bridge network on Docker is a software layer providing connectivity between containers that are connected to the same bridge network. Also, those containers are isolated from containers that are not connected to that network.

Previously when we inspected the network, we saw a network named bridge. This should be the default network that a container is attached to.

We will run an nginx container and check the network that the container will be attached to:

$ docker run --rm -p 8080:80 --name nginx-compose nginx

Now that the container is up and running, in another Terminal session, we will proceed with inspecting the network:

$ docker inspect --format '{{json .NetworkSettings.Networks }}' nginx-compose
{"bridge":{"IPAMConfig":null,"Links":null,"Aliases":null,"NetworkID":"6a149c758fc27c0c719b7c3c26b74c8f03c866ae1406ac 2902a1c45af720a79d","EndpointID":"4323e8f8bbceafcb74491e159 5073adc063fb424f87259ad1dd02078f59eeb13","Gateway":"172.17.0.1","IPAddress":"172.17.0.2","IPPrefixLen":16,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"MacAddress":"02:42:ac:11:00:02","DriverOpts":null}}

We can see that the container has been attached to the default bridge network, as we saw earlier:

$ NETWORK_ID=$(docker inspect --format '{{json .NetworkSettings .Networks.bridge.NetworkID }}' nginx-compose|sed 's/"//g')
$ docker network ls --filter ID=$NETWORK_ID
NETWORK ID NAME DRIVER SCOPE
6a149c758fc2 bridge bridge local

We can now exit the Terminal session by running the NGINX container using CTRL-C.

A user-defined bridge network is superior to using the default network. Containers resolve each other’s network location with a name or an alias:

  • Containers are attached to a network bound for their application.
  • Bridge network can be configured for the application needs.

By using the Docker host, the container is not isolated from it. The container does not have its own IP address. The container will be accessed using the host IP.

We will run the nginx instance using the host network:

$ docker run --rm --network host --name host-nginx nginx

We will test that the server is running by using another container to access the container through localhost.

In another Terminal session, let’s execute the following:

$ docker run -it --network host --rm --name nginx-wget bash wget -O- localhost:80
Connecting to localhost:80 ([::1]:80)
writing to stdout
<!DOCTYPE html>
<html>
<head>
...

Here, instead of attaching the containers to a network, we mounted them to the host network. As expected, the container doesn’t have an IP assigned; therefore, any requests to localhost are mapped to the host. This has made it feasible for the nginx-wget container to access the host-nginx container.

The networks we investigated earlier centered on Docker Engine installed on one host. Using Docker on a production with an orchestration engine such as Swarm requires the use of multiple hosts. The overlay network creates a distributed network among those hosts. An overlay network will transparently join the host networks and create a unified network on top of them. Now that we have covered Docker networking and how it works, we will proceed to check how it works with Compose.

Defining networks on a Compose configuration

Section titled “Defining networks on a Compose configuration”

So far, our containers have been running and communicating transparently. This is because when we run a Compose application, a bridge network is created. Based on our previous examples, the containers have been able to interact with other Compose services and communicate through an alias:

$ docker network ls --filter name=chapter1_default
NETWORK ID NAME DRIVER SCOPE
9ec7758d7050 chapter1_default bridge local

This can serve us for some time; however, we would like to have a different name for the network.

Adding a network in Compose is easy:

networks:
task-manager-pubic-network:
labels:
- com.packtpub.compose.app=task-manager

However, creating a network is not enough. Containers need to be attached to the network. We will reiterate the application and the services to that network. With some adaption, our Compose file should have the services under the network:

Chapter3/docker-compose.yaml
services:
task-manager:
build:
context: ../Chapter2/.
labels:
- com.packtpub.compose.app=task-manager
image: task-manager:0.1
...
networks:
- task-manager-pubic-network
labels:
- com.packtpub.compose.app=task-manager
redis:
image: redis
...
networks:
- task-manager-pubic-network
labels:
- com.packtpub.compose.app=task-manager
redis-backup:
image: bash
...
networks:
- task-manager-pubic-network
labels:
- com.packtpub.compose.app=task-manager
...
networks:
task-manager-pubic-network:
labels:
- com.packtpub.compose.app=task-manager

So, we managed to create a network for our Compose application and attach the services to it.

Next, we will put our application into action:

$ docker compose up

Since our service has the network attached, we will inspect the existing Docker networks:

$ docker network ls
NETWORK ID NAME DRIVER SCOPE
6a149c758fc2 bridge bridge local
ce5aa144f0f9 chapter3_task-manager-pubic-network bridge local
4a6d6a3e8475 host host local
be28a5cd8a16 none null local

Since all our containers have been attached to the newly created network, they are under the hood of one network. The default Compose network that was created earlier is not there.

Adding an extra network to the current application

Section titled “Adding an extra network to the current application”

So far, our containers have been running and communicating transparently, and we have managed to define the bridge network the services would use. Another thing we have observed is that the bridge network that used to be created by default no longer exists. Since we saw only one network being used at a time, we will add multiple networks in Compose.

The target for this would be our Redis database. In real life, databases usually reside on another network and are linked to your application:

networks:
redis-network:
labels:
- com.packtpub.compose.app=task-manager

We will attach the Redis database to that network:

redis:
image: redis
ports:
- 6379:6379
entrypoint: ["redis-server","/usr/local/etc/redis/redis.conf"]
volumes:
- ./redis.conf:/usr/local/etc/redis/redis.conf
- redis-data:/data
- backup:/backup
networks:
- redis-network
labels:
- com.packtpub.compose.app=task-manager

If we are curious and try to run the application, we will get an error:

{ "id": "8b171ce0-6f7b-4c22-aa6f-8b110c19f838", "name": "A task", "description": "A task that need to be executed at the timestamp specified", "timestamp": 1645275972000 }

As expected, the Go application does not have access to the network that the Redis service is attached to. We will fix this by attaching the task-manager application to the Redis network:

task-manager:
build:
context: ../Chapter2/.
labels:
- com.packtpub.compose.app=task-manager
image: task-manager:0.1
ports:
- 8080:8080
environment:
- REDIS_HOST=redis:6379
depends_on:
- redis
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/ping"]
interval: 10s
timeout: 5s
retries: 5
start_period: 5s
networks:
- task-manager-pubic-network
- redis-network

So, the container can be attached to two networks. By attaching the container to the Redis network, communication is made possible.

If we run a GET request, we should see a positive result, as follows:

curl --location --request GET 'localhost:8080/task/8b171ce0-6f7b-4c22-aa6f-8b110c19f83a'
{"task":{"id":"8b171ce0-6f7b-4c22-aa6f-8b110c19f83a","name":"A task","description":"A task that need to be executed at the timestamp specified","timestamp":1645275972000}}

In this chapter, we provisioned volumes, attached them to Compose services, and shared them between services for maintenance operations. We identified the usages of networks in Docker and how they fit into our Compose usage scenarios. By using these networks, we analyzed how a network works on Compose and how we can have multiple networks running in Compose applications.

The next chapter will focus on the Docker Compose commands. We will dive into the available commands, their purpose, and how they can assist us in managing and provisioning Compose applications.