Flask and Redis run in separate containers. Docker Compose keeps their runtime and network settings in one YAML file, and Flask connects to Redis using the service name redis. This guide shows how to start and verify both services and how to choose an update command after a change to code or configuration.
Common commands at a glance#
| Command | What it does |
|---|---|
docker compose up -d | Start services in the background and apply Compose configuration changes |
docker compose up -d --build | Build images before starting services |
docker compose up -d --no-build | Start services without building images |
docker compose restart flask | Restart the existing Flask container |
docker compose ps | Check container status for the project |
docker compose logs --tail 50 -f flask | Follow the Flask service logs starting with the last 50 lines |
docker compose config | Validate and display the merged Compose configuration |
docker compose exec flask sh | Open a shell in the running Flask container |
docker compose down | Stop services and remove the project containers and default network |
Prepare Application and Compose File#
Create the following files in a new flask-redis directory:
mkdir flask-redis && cd flask-redisapp.py: Connect to Redis and count
from flask import Flask, jsonify
import redis
import os
app = Flask(__name__)
redis_host = os.environ.get('REDIS_HOST', 'redis')
redis_port = int(os.environ.get('REDIS_PORT', 6379))
r = redis.Redis(host=redis_host, port=redis_port, decode_responses=True)
@app.route('/')
def index():
count = r.incr('visits')
return jsonify({"message": "Flask + Redis", "visits": count})REDIS_HOST and REDIS_PORT read from environment variables, defaulting to hostname redis. This name isn’t arbitrary—it corresponds to the service name in the Compose file below. Compose automatically creates a network where each service can access others by service name.
requirements.txt:
Flask==3.1.3
Werkzeug==3.1.9
gunicorn==27.0.1
redis==8.1.0Added redis Python client.
Dockerfile: Reuse the multi-stage build from article 4 and add the Redis client to the dependency list.
FROM python:3.11-slim AS python-base
FROM python-base AS builder
WORKDIR /build
COPY requirements.txt .
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir -r requirements.txt
FROM python-base AS runtime
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY app.py .
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]compose.yaml: Declare two services
services:
flask:
build: .
image: flask-redis:1.0
ports:
- "127.0.0.1:8000:8000"
environment:
REDIS_HOST: redis
REDIS_PORT: 6379
depends_on:
redis:
condition: service_healthy
redis:
image: redis:7.4-alpine
command: redis-server --save 60 1
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 2s
timeout: 1s
retries: 15Run docker compose config to validate the Compose file and inspect the resolved configuration before starting the services. This example defines no environment-variable placeholders, so the output should not contain unresolved variables.
Under services, two services are defined: flask and redis.
Compose gives both services a shared network. Flask reaches Redis at redis:6379 without publishing Redis to the host. Flask is published on the host’s loopback address for the local exercise.
redis-cli ping checks whether Redis can respond. With service_healthy, Compose waits for that check during initial startup before starting Flask, but it does not reconnect the application after a later Redis failure. This example does not implement Redis retries, so requests may fail while Redis is unavailable. --save 60 1 takes a snapshot when at least 60 seconds have passed and at least one change has been made. The snapshot is stored in the container’s writable layer; because this example has no named volume, it is not guaranteed to survive container removal or a later down and up. The counter is only a demonstration, not a persistent data setup.
flowchart TD
accTitle: Flask and Redis in Compose
accDescr: The browser reaches Flask through host port 8000. Flask connects to redis:6379 within the Compose network. The Redis port is unpublished.
browser["Browser on host · localhost:8000"] -->|"Published as 127.0.0.1:8000:8000"| flask
subgraph project["Default Compose network"]
direction TB
flask["flask service · 8000"] -->|"redis:6379"| redis["redis service · 6379"]
endStart and Access Services#
From the directory containing compose.yaml, start the services and check their state.
docker compose up -d --build
docker compose psRedis should be healthy and Flask should be running. Send two requests.
curl http://127.0.0.1:8000
curl http://127.0.0.1:8000In a fresh project, the two responses contain "visits":1 and "visits":2. Existing projects may start at a higher count.
Choose a command after a change#
| What changed | Command | What to expect |
|---|---|---|
| Application code copied into the image | docker compose up -d --build | Build the image with the usual cache. Compose recreates affected containers if the image changes. |
Settings in compose.yaml | docker compose up -d | Apply the settings by recreating affected containers. Compose may still pull or build missing images according to its policy. |
| Configuration changed and you want to forbid builds | docker compose up -d --no-build | Apply settings without building. The required images must be available locally or from a registry according to the pull policy. |
| You only want to restart Flask | docker compose restart flask | Restart the existing Flask container with its current image and settings. |
Run docker compose ps and repeat the HTTP request after a change. To keep the example consistent, change the Flask response text to test a code change, or change the published port and use the new port in curl to test a configuration change.
View Logs and Enter Containers#
View all service logs:
docker compose logsView only one service’s logs:
docker compose logs flaskTo follow new output from Flask, start with the last 50 lines. flask is the service name in compose.yaml.
docker compose logs --tail 50 -f flaskThese options work the same way as in the single-container logging example.
Enter the Flask container:
docker compose exec flask shLike docker exec, docker compose exec requires a running container. Here the service name selects Flask, and sh starts a shell inside its container.
Stop and clean up the example#
docker compose downThis removes the project containers and its default network. Images stay local. A simple restart keeps the existing Redis container and its storage. After down and a fresh up, Compose will not reuse the Redis image’s anonymous volume automatically, so this exercise starts with an empty counter. Use a named volume for data that should survive container recreation. The storage guide explains the difference.
Common Issues#
If Flask cannot connect to Redis, check
docker compose ps,docker compose logs redis, and the value ofREDIS_HOST. From the Flask container,localhostis Flask itself.Requests fail while Redis is temporarily unavailable. This example has no application-level retries, so Flask may return HTTP 500. Check
docker compose psanddocker compose logs redis; after Redis recovers, send another request to verify that the counter works again. For this local exercise, you can also restart Redis and wait for its health check:Shelldocker compose restart redis docker compose ps curl http://127.0.0.1:8000restartrestarts the existing Redis container; a health check does not guarantee ongoing availability. Production applications also need to handle connection errors, retries, and timeouts.If HTTP requests still return the old response after a source edit, check that the edited file is the one copied in the Dockerfile, then run
docker compose up -d --build.