Docker Compose: Run Flask and Redis

·1225 words

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
#

CommandWhat it does
docker compose up -dStart services in the background and apply Compose configuration changes
docker compose up -d --buildBuild images before starting services
docker compose up -d --no-buildStart services without building images
docker compose restart flaskRestart the existing Flask container
docker compose psCheck container status for the project
docker compose logs --tail 50 -f flaskFollow the Flask service logs starting with the last 50 lines
docker compose configValidate and display the merged Compose configuration
docker compose exec flask shOpen a shell in the running Flask container
docker compose downStop services and remove the project containers and default network

Prepare Application and Compose File
#

Create the following files in a new flask-redis directory:

Shell
mkdir flask-redis && cd flask-redis

app.py: Connect to Redis and count

Python
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:

Text
Flask==3.1.3
Werkzeug==3.1.9
gunicorn==27.0.1
redis==8.1.0

Added redis Python client.

Dockerfile: Reuse the multi-stage build from article 4 and add the Redis client to the dependency list.

Dockerfile
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

YAML
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: 15

Run 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"]
    end

Start and Access Services
#

From the directory containing compose.yaml, start the services and check their state.

Shell
docker compose up -d --build
docker compose ps

Redis should be healthy and Flask should be running. Send two requests.

Shell
curl http://127.0.0.1:8000
curl http://127.0.0.1:8000

In 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 changedCommandWhat to expect
Application code copied into the imagedocker compose up -d --buildBuild the image with the usual cache. Compose recreates affected containers if the image changes.
Settings in compose.yamldocker compose up -dApply 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 buildsdocker compose up -d --no-buildApply settings without building. The required images must be available locally or from a registry according to the pull policy.
You only want to restart Flaskdocker compose restart flaskRestart 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:

Shell
docker compose logs

View only one service’s logs:

Shell
docker compose logs flask

To follow new output from Flask, start with the last 50 lines. flask is the service name in compose.yaml.

Shell
docker compose logs --tail 50 -f flask

These options work the same way as in the single-container logging example.

Enter the Flask container:

Shell
docker compose exec flask sh

Like 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
#

Shell
docker compose down

This 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 of REDIS_HOST. From the Flask container, localhost is 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 ps and docker 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:

    Shell
    docker compose restart redis
    docker compose ps
    curl http://127.0.0.1:8000

    restart restarts 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.

References
#