Skip to content
ImagineWorld

Running the First Application Using Compose

node_idnode-book_a-developer-s-essential-guide-to-docker-compose_chapter-02-running-the-first-application-using-compose
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleRunning the First Application Using Compose
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Running the First Application Using Compose

Section titled “Chapter 2 — Running the First Application Using Compose”

In the previous chapter, we learned about Docker Compose and how we can benefit from its features. We learned how it works and interacts with the Docker engine and how it integrates with the Docker command-line interface (CLI). By installing Compose on the workstation of our choice, we were able to run some application examples.

Using Compose throughout an application’s development can be a streamlined process that can have a significant role in increasing productivity. By the time you have completed this chapter, you will be able to package your application and run it on Compose. You’ll be able to interact with the application and enhance its functionality by interacting with a database. Once the basic multi-container application is deployed using Compose, we shall dive deeper into more Compose functionalities such as health checks, labels, environment variables, and command override.

We will cover the following main topics in this chapter:

  • Creating a core application
  • Running Redis using Compose
  • Shelling into a container managed by Compose
  • Interacting with a Docker Compose service
  • Packaging your application with Docker and Compose
  • Running your multi-container application using Compose

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

In this section, we will create an application using the Go programming language. Throughout the course of this book, this application will evolve and will help us display the features that Compose offers. Go is an open source programming language. Many software applications that we use nowadays are built using Go, including Docker, Kubernetes, and Compose. By programming using Go, we benefit from a robust library providing packages that we need such as http server, testing utils, and more.

Installing Go on your workstation is streamlined. By navigating to the download page on https://go.dev/doc/install, you can find installation packages for the major operating systems.

Building a REST API in Go can be done either by using the existing libraries or by using a framework. We will pick the framework option in order to keep our code base simple and keep our focus on Compose. The framework we will use is Gin (https://gin-gonic.com/), a popular Go framework that will assist us in routing, rendering JSON, and avoiding writing extra code should we use only the existing Go libraries.

Let’s create our module with the following:

$ go mod init task_manager

We shall use an application template to get started:

$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go

Now, we are going to download Gin:

$ go get github.com/gin-gonic/gin

Following that, we will build the module using the build command of go:

$ go build

Now, you can run the application using go run:

$ go run main.go

Next, we shall test the application using curl:

$ curl http://localhost:8080/user/John
{"status":"no value","user":"John"}

We have successfully created our first REST API using Go. We have the tools to get started and develop our application. The next step is to build upon the template we just used and create our core application.

The application will be a Task Manager available using a REST API interface. The application user will submit a task using a POST request. The user will also be able to retrieve the tasks using a GET request as well as delete them using a DELETE request. The endpoints we should cover for now are as follows:

  • GET /task: Retrieve all tasks.
  • POST /task: Add task.
  • GET /task/{id}: Retrieve task by ID.
  • DELETE /task/{id}: Delete task by ID.

With some adaptions to the main.go method, we will transform the class to the task server. The current implementation will keep the tasks in memory. The application can be in one file, as we can see at https://raw.githubusercontent.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose/main/Chapter2/example-task-manager/main.go.

Our data structure will contain an ID, the name of the task, the description, and the timestamp:

type Task struct {
Id string \`json:"id"\`
Name string \`json:"name"\`
Description string \`json:"description"\`
Timestamp int64 \`json:"timestamp"\`
}

Here, we can see the corresponding controllers for the actions mentioned:

// Get tasks
r.GET("/task", func(c *gin.Context) {
tasks := []Task{}
for _, v := range taskMap {
tasks = append(tasks, v)
}
c.JSON(http.StatusOK, gin.H{"tasks": tasks})
})
// Get task
r.GET("/task/:id", func(c *gin.Context) {
id := c.Params.ByName("id")
task, ok := taskMap[id]
if ok {
c.JSON(http.StatusOK, gin.H{"task": task})
} else {
c.JSON(http.StatusNotFound, gin.H{"id": id, "message": "not found"})
}
})
// Add task
r.POST("/task", func(c *gin.Context) {
var task Task
if err := c.BindJSON(&task); err != nil {
c.JSON(http.StatusOK, gin.H{"task": task, "created": false, "message": err.Error()})
} else {
taskMap[task.Id] = task
c.JSON(http.StatusCreated, gin.H{"task": task, "created": true, "message": "Task Created Successfully"})
}
})
// Remove task
r.DELETE("/task/:id", func(c *gin.Context) {
id := c.Params.ByName("id")
delete(taskMap, id)
c.JSON(http.StatusOK, gin.H{"id": id, "message": "deleted"})
})

Since our REST API is up and running, we will interact with it by issuing some calls using curl. To issue a create task request, enter the following command:

$ curl --location --request POST 'localhost:8080/task/' \
--header 'Content-Type: application/json' \
--data-raw '{
"id": "8b171ce0-6f7b-4c22-aa6f-8b110c19f83a",
"name": "A task",
"description": "A task that need to be executed at the timestamp specified",
"timestamp": 1645275972000
}'
{"created":true,"message":"Task Created Successfully","task":{"id":"8b171ce0-6f7b-4c22-aa6f-8b110c19f83a","name":"A task","description":"A task that need to be executed at the timestamp specified","timestamp":1645275972000}}

To issue a get all tasks request, enter the following command:

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

To retrieve a specific task using a task ID, enter the following command:

$ 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 order to keep our example requests simple and portable, we used curl. As Postman is a popular tool for interacting with REST APIs, a collection is available here: https://github.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose/blob/main/Chapter2/Task-Manager.postman_collection.json.

So far, we’ve created a Task Manager application that provides a REST API. Then, by using curl, we tested the application’s functionality. Onward, we will adapt the Task Manager application to use a Redis server for storage.

Our main application is set up. For simplicity purposes, instead of storing the tasks in a database, we used an in-memory map. This works well for prototyping; however, our data and tasks remain only in one process. In the case of spinning up two instances of our application, each instance will contain different tasks.

To tackle this, we will store the data in a database. This way, the data will be kept in one place and there will not be any differences in the tasks served by various instances. Redis will be our choice for storing the data.

Redis is a popular in-memory data structure storage. It’s widely used as a cache, and all major cloud providers use it as a caching offering. Components such as ElastiCache in Amazon Web Services (https://aws.amazon.com/elasticache) or Memorystore in Google Cloud Platform (https://cloud.google.com/memorystore) have the option of using Redis. Also, Redis can be used for database purposes. Furthermore, it comes with broker and streaming capabilities. Throughout this book, Redis and its versatility will help us highlight the features of Docker Compose.

In order to run Redis, we will use Docker Compose. Therefore, let’s create a Compose file with a Redis service:

services:
redis:
image: redis
ports:
- 6379:6379

The service name will be redis. The default port of Redis is 6379, so we shall bind it locally to port 6379. By running compose up, we should be able to interact with a redis database locally:

$ docker compose up
…
chapter2-redis-1 | 1:M 19 Feb 2022 14:18:20.302 # Server initialized
chapter2-redis-1 | 1:M 19 Feb 2022 14:18:20.303 * Ready to accept connections

A Redis database is up and running through Compose and is ready to accept connections. In the next section, we will shell into the Redis container, get familiar with it, and execute some commands.

Shelling into a container managed by Compose

Section titled “Shelling into a container managed by Compose”

Since we’ve been successful in running a Redis database using Compose, we will run some commands upon that Redis instance and get familiar with the database. As happens with many container-based distributions of databases, along with the actual database, the image can contain tools that help the user interact with the database for administrative or usage purposes.

The Redis CLI can be used to send commands to a Redis service. The Redis Docker image does contain the Redis CLI, so we should be able to use it with the running database.

Let’s find our running Redis image:

$ docker ps --format "{{.Names}}"
chapter2-redis-1
$

Let’s shell into this image:

$ docker exec -it chapter2-redis-1 bash
root@d189b089bcf6:/data#

We just shelled successfully into a container managed by Compose. Let’s navigate and see what is already there:

$ root@d189b089bcf6:/data# ls
dump.rdb
root@d189b089bcf6:/data# ls /usr/local/bin
docker-entrypoint.sh gosu redis-benchmark redis-check-aof redis-check-rdb redis-cli redis-sentinel redis-server

The default directory has a dump.rdb file. Also, by using ls, we can see the binaries such as redis-server, redis-sentinel, and redis-cli. Since the Redis CLI does exist on the image, we can execute some commands upon the running Redis server:

$ root@d189b089bcf6:/data# redis-cli
127.0.0.1:6379>

Redis will be the main storage for tasks, so we shall add a task ID using ZADD and then check the data stored:

127.0.0.1:6379> ZADD tasks 1645275972000 "8b171ce0-6f7b-4c22-aa6f-8b110c19f83a"
(integer) 1
127.0.0.1:6379> ZRANGE tasks 0 -1 WITHSCORES
1) "8b171ce0-6f7b-4c22-aa6f-8b110c19f83a"
2) "1645275972000"

After running a Redis server using Compose successfully, we managed to shell into the Redis container, identified existing command-line tools, and used the redis-cli command to interact with the server. Next, we’ll adapt our application in order to use the Redis server for storage purposes.

We ran Redis on Compose and we shelled to that instance in order to run some commands and add data. Obviously, interacting with that instance doesn’t require us to shell on it. The instance has been configured to have the port 6379 bound to our local port 6379.

For example, we should be able to interact with that instance by a redis-cli client that has localhost access. In the following, you can see another Redis Docker image accessing our Compose-managed Redis:

$ docker run --rm -it --entrypoint bash redis -c 'redis-cli -h host.docker.internal -p 6379'
host.docker.internal:6379> ZRANGE tasks 0 -1 WITHSCORES
1) "8b171ce0-6f7b-4c22-aa6f-8b110c19f83a"
2) "1645275972000"
host.docker.internal:6379>

We can see that the entry that we added previously has been displayed on this terminal session. We are successfully interacting with the Compose service from the outside, so we shall proceed with adapting our application’s code base in order to use Redis instead of an in-memory map. One structure to use would be a sorted set. A sorted set is like a set accompanied by a numerical value called a score. The elements on the set are sorted by the score. If they have the same score, then they are sorted based on the lexicographic order of the value. If we examine the Redis ZADD command that we ran previously, we can see that the score that we specified is actually the task’s timestamp. So, the tasks on our services will be sorted using the timestamp.

Also, we want to retrieve tasks by id. Hashes are a good option since they are the perfect data type to represent objects. By using a hash, we can map and access the struct values in a key-value manner:

host.docker.internal:6379> HMSET task:8b171ce0-6f7b-4c22-aa6f-8b110c19f83 Id 8b171ce0-6f7b-4c22-aa6f-8b110c19f83a Name "A task" Description "A task that need to be executed at the timestamp specified" Timestamp 1645275972000
OK
host.docker.internal:6379> HGETALL task:8b171ce0-6f7b-4c22-aa6f-8b110c19f83
1) "Id"
2) "8b171ce0-6f7b-4c22-aa6f-8b110c19f83a"
3) "Name"
4) "A task"
5) "Description"
6) "A task that need to be executed at the timestamp specified"
7) "Timestamp"
8) "1645275972000"
host.docker.internal:6379>

Let’s exit and terminate the container using Ctrl + C.

Now, we will adapt our application to use Redis for persistence. There are various client options, so we will choose the one that is currently more popular, which is the go-redis/redis client.

Let’s import go-redis/redis on our project:

$ go get github.com/go-redis/redis/v8

After some changes, our code base should serve requests using Redis. We can see the Redis persistence operations on GitHub: https://github.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose/blob/main/Chapter2/main.go#L91.

Also, the methods of the controller will be adapted accordingly, as we can see on GitHub: https://github.com/PacktPublishing/A-Developer-s-Essential-Guide-to-Docker-Compose/blob/main/Chapter2/main.go#L39.

For every task, there will be an equivalent hash. The prefix of the hash will be the string task. The hash will contain all the information submitted for a task. In order to have some sorting based on the date of the task, we will use a sorted set.

This brings us to the following Redis interactions per endpoint:

  • GET /task: Retrieve task ID using the sorted set and fetch the hash for each task.
  • POST /task: Add a hash named task:{id} for the task and insert the ID into the sorted set.
  • GET /task/{id}: Retrieve the task hash using key task:{id}.
  • DELETE /task/{id}: Remove the hash named task:{id} and remove the ID entry from the sorted set.

Let’s run our application using the updated code base:

$ go run main.go

By running a Redis server using Compose, we’ve been able to migrate the existing core application to a Redis-backed solution. The code changes applied helped to replace the app-based storage with the appropriate Redis data structures for our use case. In the next section, we will package the application using Docker and run it using Compose.

Packaging your application with Docker and Compose

Section titled “Packaging your application with Docker and Compose”

It’s time that we moved on to packaging and deploying our application using Compose. In order to achieve this, the requisite is to create a Docker image for our application. Before we go in that direction, we need to adapt our code base so it can run in different environments without having to change the code and generate another image.

By examining the code base, we can see that certain configurations are subject to change. Redis configuration should be flexible since a Redis server, as long as it is accessible to our code base, can be located everywhere. For this reason, the Redis client will derive the configurations through environment variables. However, if there were no configurations provided, it should fall back to a default configuration.

The following utility function will assist us with this. In the case of no environment variable being provided, a default value will be used:

func getIntEnv(key string, defaultvaule int) int {
if value := os.Getenv(key); len(value) == 0 {
return defaultvaule
} else {
if i, err := strconv.Atoi(value); err == nil {
return i
} else {
return defaultvaule
}
}
}
func getStrEnv(key string, defaultValue string) string {
if value := os.Getenv(key); len(value) == 0 {
return defaultValue
} else {
return value
}
}

Onward, we will adapt the Redis client configuration to use environment variables:

var (
client = redis.NewClient(&redis.Options{
Addr: getStrEnv("REDIS_HOST", "localhost:6379"),
Password: getStrEnv("REDIS_PASSWORD", ""),
DB: getIntEnv("REDIS_DB", 0),
})
taskMap = make(map[string]Task)
)

Finally, let’s configure the host and port that our server will operate on:

func main() {
r := setupRouter()
r.Run(getStrEnv("TASK_MANAGER_HOST", ":8080"))
}

So far, we have adapted the existing code base to be configured through environment variables. This makes our solution portable in different environments. If no extra configuration is provided, our application can fall back to the default settings. We can now proceed to create a Docker image for the application.

Thanks to our previous changes, our code base can now be containerized and run in different environments. This will be the Dockerfile for the application:

# syntax=docker/dockerfile:1
FROM golang:1.17-alpine
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o /task_manager
EXPOSE 8080
CMD [ "/task_manager" ]

Let’s examine the steps:

  1. We specify the syntax to use when parsing the Dockerfile.
  2. A golang alpine -based image is used.
  3. /app is the directory the application will reside in and its dependencies.
  4. mod and sum files are copied.
  5. The command to download the dependencies is issued.
  6. Our application files are copied.
  7. The main application is built.
  8. The port the application should run on is defined.
  9. Our service is running.

Let’s build our image:

$ docker build . -t task-manager:0.1

By creating a Dockerfile, we can now package our application in a Docker image and run it using the Docker CLI or Compose.

Since our image is built, we can run our Docker image:

$ docker run --rm -p 8080:8080 --env REDIS_HOST=host.docker.internal:6379 task-manager:0.1

The application will work as expected and as you can see, we specified it using the Redis host. Instead of using the Redis host, let’s try to use the Redis container running on Compose. Since Redis is already running on Compose, it should be bound to the network created by Compose. We can find the network by listing the Docker networks present:

$ docker network ls
NETWORK ID NAME DRIVER SCOPE
1392d8a87032 bridge bridge local
…
453bafcfd97a chapter2_default bridge local
4a6d6a3e8475 host host local
…

We will mount the container to the chapter2_default network:

$ docker run --rm -p 8080:8080 --env REDIS_HOST=redis:6379 --network=chapter2_default task-manager:0.1

Take note that we changed the host. Because the container runs on the same network, the Redis instance can be accessed by using the service name, which will be resolved to the IP address inside the network.

Now that we have built the images instead of running them as standalone, we can add them to the Compose file:

services:
task-manager:
image: task-manager:0.1
ports:
- 8080:8080
environment:
- REDIS_HOST=redis:6379
redis:
image: redis
ports:
- 6379:6379

Let’s break down how it works:

  • Both services run on Compose.
  • Since no network is specified, they use both the default network.
  • By being on the same network, they can access each other using the service name.
  • Any environment variables needed are set in the environment section.

We will recreate the application so that our changes will take effect:

$ docker compose up --force-recreate

Our multi-container application is now fully running on Compose, operating through the same network.

By now, we have packaged our application fully using Compose. One of the things we spotted is that, throughout the chapter, our original application changed a lot. From a map-based Task Manager, it became an application backed by a Redis database with some configuration options. As expected, these will not be the last changes to the code base. The code base will get more changes in the future and, therefore, it’s important to run our application on Compose in a more automated way.

Instead of building an image and changing to the new version using the image section of Compose, we should instruct Compose to build the image for us and run it. This is what you need to set up Compose to use the Dockerfile in order to build and use the image behind the scenes:

services:
task-manager:
build: .
ports:
- 8080:8080
environment:
- REDIS_HOST=redis:6379
redis:
image: redis
ports:
- 6379:6379

Since the image happens to have both the Dockerfile and docker-compose.yaml on the same directory, by using build ., we point to the same directory. In a scenario where the code base is on another image, we have the option to specify a path and run Compose with multiple directories and even different projects involved.

So far, we got used to using the Task Manager through an image name. We will try to do the same thing on Compose by defining both build and image. By using build and image, the image will be built as expected and will then be tagged based on the name given using image:

services:
task-manager:
build: .
image: task-manager:0.1

From building a Docker image using the Docker CLI manually, we executed the build process using Compose. The foundation for using Compose with our application has been established, so we can proceed with more advanced concepts of Compose.

Running your multi-container application using Compose

Section titled “Running your multi-container application using Compose”

By having our multi-container application up and running on Compose, we can now jump on more specific concepts and identify how to get the most out of our application on local development.

Our code base has an extra endpoint that we did not mention previously, known as the ping endpoint. As seen on the code base, it’s an endpoint replying with a constant message once invoked:

// Health Check
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
})

This endpoint will be leveraged as a health check. As long as the application is running, it will always give back a response. Should there be something wrong with the application, the endpoint will not reply, and so will be marked unhealthy.

By adding a health check using Compose, we instruct a command to be run on the container. Based on how the command exits and the time threshold, the container will be marked as healthy or unhealthy. The command will be executed inside the container. Using a non-existing command will result in a failed health check.

The command can be everything executable on the container. It can be an existing command on the container or even a customized script with a complex health check algorithm. What Compose will consider is the successful execution of the script within the right time limit.

Since our health check endpoint is implemented on http server, we need a command to run on it. cURL is a very good choice; therefore, we will adapt the Dockerfile and add it to the image:

# syntax=docker/dockerfile:1
FROM golang:1.17-alpine
RUN apk add curl
…

Let’s build the latest image by using compose build:

$ docker compose build

We have curl installed on the image; therefore, a health check will be added, utilizing the command:

services:
task-manager:
build: .
image: task-manager:0.1
ports:
- 8080:8080
environment:
- REDIS_HOST=redis:6379
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/ping"]
interval: 20s
timeout: 10s
retries: 5
start_period: 5s

Every 20 seconds after an initial period of 5 seconds, a ping to task-manager will be issued using curl with a timeout of 10 seconds. In case of failure, there should be five retries before marking the instance unhealthy. By using curl with -f, there will be a failure on non-successful requests such as 5XX responses.

If we run the application, we can observe from the logs that health check requests are being issued:

$ docker compose up
…
chapter2-task-manager-1 | [GIN] 2022/02/20 - 17:23:07 | 200 | 8.584µs | 127.0.0.1 | GET "/ping"
chapter2-task-manager-1 | [GIN] 2022/02/20 - 17:23:27 | 200 | 34.459µs | 127.0.0.1 | GET "/ping"
chapter2-task-manager-1 | [GIN] 2022/02/20 - 17:23:47 | 200 | 42.458µs | 127.0.0.1 | GET "/ping"

On another shell, let’s check the running containers:

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
20c6d1cb557b task-manager:0.1 "/task_manager" 4 seconds ago Up 3 seconds (health: starting) 0.0.0.0:8080->8080/tcp chapter2-task-manager-1
$ docker ps
20c6d1cb557b task-manager:0.1 "/task_manager" 2 minutes ago Up 44 seconds (healthy) 0.0.0.0:8080->8080/tcp chapter2-task-manager-1

We can take it a bit further and set the endpoint to fail, so that we can see the service marked as unhealthy:

// Health Check
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusInternalServerError, "pong")
})

After some time, the container is indeed marked unhealthy:

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
20c6d1cb557b task-manager:0.1 "/task_manager" 2 minutes ago Up 2 minutes (unhealthy) 0.0.0.0:8080->8080/tcp chapter2-task-manager-1

We investigated the health-check capabilities of Compose and managed to reproduce successful or failed health check scenarios.

The task-manager service depends on Redis. Provided the redis service is not up and running, task-manager will not be operational. For this case, we can instruct the service not to run until the service depending on it is fully running:

services:
task-manager:
build: .
image: task-manager:0.1
ports:
- 8080:8080
environment:
- REDIS_HOST=redis:6379
depends_on:
- redis

ENTRYPOINT, arguments, and environment variables

Section titled “ENTRYPOINT, arguments, and environment variables”

Supposing that before we run the task-manager service, we also want to load the Redis database with some data. There are various ways to achieve this. Our choice would be to run another redis container using the Redis CLI. To do so, we need to override the entry point and specify some custom arguments.

Let’s start with our initial service:

redis-populate:
image: redis
depends_on:
- redis

It is not functional for now, but we will build on it.

Since we already used environment variables using the key-value method, we will try using a file. The environment variable file will contain the host and the port the Redis CLI should connect to:

HOST=redis
PORT=6379

The next step is to mount env file to the redis-populate service:

redis-populate:
image: redis
depends_on:
- redis
env_file:
- ./env.redis-populate

Having a script that executes commands on the Redis CLI can be possible with a few tweaks. Suppose we want to add a task before starting the application; we would put the commands needed in a txt file:

HMSET task:a3a597d1-26f8-43e5-be05-81373f2c0dc3 Id a3a597d1-26f8-43e5-be05-81373f2c0dc3 Name "Existing Task" Description "A task that was here before" Timestamp 1645393434000
ZADD tasks 1645393434000 "a3a597d1-26f8-43e5-be05-81373f2c0dc3"

By using piping, we will actually forward the commands to be executed by the Redis CLI. The environment variable can also help to execute the commands to different servers. The script that will execute Redis commands from the txt file should look like this:

#!/bin/sh
cat $1| redis-cli -h $HOST -p $PORT

Those commands will be wrapped to an executable script and mounted to the redis-populate container:

redis-populate:
image: redis
depends_on:
- redis
env_file:
- ./env.redis-populate
volumes:
- ./redis-populate.txt:/redis-populate.txt
- ./redis-populate.sh:/redis-populate.sh

In order to run the script and populate the database, we need to change entrypoint on Docker:

redis-populate:
image: redis
entrypoint: ["/redis-populate.sh","/redis-populate.txt"]
depends_on:
- redis
env_file:
- ./env.redis-populate
volumes:
- ./redis-populate.txt:/redis-populate.txt
- ./redis-populate.sh:/redis-populate.sh

Thanks to the custom ENTRYPOINT and the environment variables, we should be able to have some data preloaded to our application.

Labels are a Docker feature that can be used on Compose. Through labels, we can apply metadata to Docker objects such as images, containers, networks, and volumes. This makes organizing the apps easier, for example, logical grouping or searching resources by using label filters.

By building the image, we can specify a label:

build:
context: .
labels:
- com.packtpub.compose.app=task-manager

Then, we can filter related images using that label:

$ docker images --filter "label=com.packtpub.compose.app=task-manager"
REPOSITORY TAG IMAGE ID CREATED SIZE
task-manager 0.1 de4b8f7c9fff 15 hours ago 529MB

In the service section, we can add a tag to the container:

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

Then, we can filter containers using that label:

docker images --filter "label=com.packtpub.compose.app=task-manager"
$ docker ps --filter="label=com.packtpub.compose.app=task-manager"
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
98c45777bdcd redis "docker-entrypoint.s…" 58 seconds ago Up 57 seconds 0.0.0.0:6379->6379/tcp chapter2-redis-1

We have been successful in packaging our application using Compose, creating the Docker image, and labeling it. This helped with running an application on Compose end-to-end, from the implementation of the code base until running it on a Docker container.

In this chapter, we created a multi-container application running on Docker Compose and used Compose features such as building and tagging an image, communicating between containers using the same network, health checks, labeling, and ENTRYPOINT configuration. Those features make it easier to transition from manual Docker-based management to a Compose-based one. By being able to package a complex application, we lay the foundation for deploying and distributing our multi-container application using Compose.

The next chapter is about networking and volume management, including understanding how the concept of Docker volumes and networks is mapped to Compose.