Docker Compose best practices
Docker Compose provides a declarative way of managing Docker container configuration. This enables GitOps for your Docker workloads. While Docker Compose is primarily used in development environments, you can use it in production very effectively, especially when Docker runs in production and does not use another container orchestrator such as Kubernetes.
Always use docker-compose.yml files alongside code
The YAML file defines how to run your containers. So, it becomes a valuable tool for declaratively building and deploying your containers from a single space. You can add all dependencies to your application and run related applications in a single network.
Separate multiple environment YAMLs using overrides
Docker Compose YAML files allow us to both build and deploy Docker images. Docker has enabled the build once, run anywhere concept. This means we build once in the development environment and then use the created image in subsequent environments. So, the question arises of how we can achieve that. Docker Compose allows us to apply multiple YAML files in a sequence where the next configuration overrides the last. That way, we can have separate override files for various environments and manage multiple environments using a set of these files.
For example, say we have the following base docker-compose.yaml file:
version: “2.4”
services:
flask:
image: “bharamicrosystems/python-flask-redis:latest”
ports:
- “80:5000”
networks:
- flask-app-net
redis:
image: “redis:alpine” networks:
- flask-app-net
command: [“redis-server”, “–appendonly”, “yes”]
volumes:
- redis-data:/data networks:
flask-app-net: driver: bridge
volumes: redis-data:
We only have to build the Flask application container image in the development environment so that we can create an override file for the development environment – that is, docker-compose. override.yaml:
web:
build: .
environment:
DEBUG: ‘true’
redis:
ports:
– 6379:6379
Here, we added a build parameter within the web service. This means the Python Flask application will be rebuilt and then deployed. We also set the DEBUG environment variable within the web service and exposed the redis port to the host filesystem. This makes sense in the development environment, as we might want to debug Redis from the development machine directly. Still, we would not want something of that sort in the production environment. Therefore, the default docker-compose. yaml file will work in the production environment, as we saw in the previous section.