Manage Docker containers with the SDK to perform blue/green deployment. Identify the running blue container, spin up green, wait for healthcheck to pass, update Nginx config to point to green, then stop blue.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Preparing a Python example for blue/green Docker deployment
A detailed plan is ready to produce a full Python script using the Docker SDK that identifies the running “blue” container, spins up a “green” container, waits for its healthcheck to pass, updates the Nginx config with the green container’s IP, reloads Nginx, and then stops the blue container. The script will demonstrate labeling, healthcheck polling, config editing, and container management.
Below is an example Python script using the Docker SDK (docker‑py) to perform a simple blue/green deployment:
It finds the currently running blue container (by label).
Starts a green container from the same image.
Waits until the green container’s health check reports healthy.
Updates an Nginx config snippet to point to the green container.
Reloads Nginx.
Stops the blue container.
You can adapt labels, port mappings, network, and file paths to your environment.
python
import time
import docker
import subprocess
# -------------------------------------------------------------------
# Configuration
# -------------------------------------------------------------------
# How we identify the current "blue" container:
BLUE_LABEL = {"app": "mywebapp", "color": "blue"}
# Label for the new "green" container:
GREEN_LABEL = {"app": "mywebapp", "color": "green"}
# Docker image to run for green:
IMAGE_NAME = "myregistry/mywebapp:latest"
# Nginx upstream block file location:
NGINX_UPSTREAM_FILE = "/etc/nginx/conf.d/upstream_app.conf"
# Example content we might write:
NGINX_UPSTREAM_TEMPLATE = """
upstream mywebapp_upstream {{
server {target_host}:{target_port};
}}
"""
# Name of the Nginx container if you're running Nginx in Docker:
NGINX_CONTAINER_NAME = "nginx-proxy"
# Or if Nginx runs on the host, use host command:
# NGINX_RELOAD_COMMAND = ["nginx", "-s", "reload"]
NGINX_RELOAD_COMMAND = ["docker", "exec", NGINX_CONTAINER_NAME, "nginx", "-s", "reload"]
# Port on which your app listens inside the container:
APP_PORT = 8080
# Docker network (if needed for stable container DNS):
DOCKER_NETWORK = "myapp-net"
# Health check timeout (seconds):
HEALTH_TIMEOUT = 120
CHECK_INTERVAL = 3
# -------------------------------------------------------------------
# Script
# -------------------------------------------------------------------
client = docker.from_env()
def get_running_blue_container():
# Finds the first running container with label color=blue (and any other labels you set)
containers = client.containers.list(
filters={"label": [f"{k}={v}" for k, v in BLUE_LABEL.items()]}
)
return containers[0] if containers else None
def run_green_container():
# Start a new container with label color=green
# If your image defines a HEALTHCHECK in its Dockerfile, docker will populate State.Health
container = client.containers.run(
IMAGE_NAME,
detach=True,
labels=GREEN_LABEL,
name="mywebapp-green", # optional explicit name
network=DOCKER_NETWORK,
# environment={"SOME_VAR": "VALUE"}, # if needed
# ports={"8080/tcp": 8081}, # if you need host port mapping
)
return container
def wait_for_health(container, timeout=HEALTH_TIMEOUT):
# Wait until container's health is "healthy" or we time out
start = time.time()
while True:
container.reload()
health = container.attrs.get("State", {}).get("Health", {})
status = health.get("Status")
if status == "healthy":
print(f"Container {container.name} is healthy.")
break
if time.time() - start > timeout:
raise RuntimeError(f"Container {container.name} failed to become healthy in time.")
print(f"Waiting for {container.name} to become healthy. Current status: {status}")
time.sleep(CHECK_INTERVAL)
def update_nginx_upstream(container_ip, container_port):
"""
Writes a simple upstream config file that points Nginx at container_ip:container_port,
then reloads Nginx.
"""
new_conf = NGINX_UPSTREAM_TEMPLATE.format(
target_host=container_ip,
target_port=container_port,
)
with open(NGINX_UPSTREAM_FILE, "w") as f:
f.write(new_conf)
print(f"Updated {NGINX_UPSTREAM_FILE} to {container_ip}:{container_port}")
# Reload Nginx
subprocess.run(NGINX_RELOAD_COMMAND, check=True)
print("Nginx reloaded.")
def main():
# 1) Identify running blue container
blue = get_running_blue_container()
if not blue:
print("No running 'blue' container found; starting from scratch.")
else:
print(f"Found running blue container: {blue.name}")
# 2) Spin up green container
green = run_green_container()
print(f"Started green container: {green.name}")
# 3) Wait for green health check
wait_for_health(green)
# 4) Get green container IP
green.reload()
network_settings = green.attrs.get("NetworkSettings", {})
# If using a user-defined bridge network, find IP in NetworkSettings["Networks"][DOCKER_NETWORK]["IPAddress"]
green_ip = network_settings["Networks"][DOCKER_NETWORK]["IPAddress"]
print(f"Green container IP: {green_ip}")
# 5) Update Nginx to point to green
update_nginx_upstream(green_ip, APP_PORT)
# 6) Stop blue container
if blue:
print(f"Stopping blue container {blue.name}...")
blue.stop(timeout=10)
print(f"Blue container {blue.name} stopped.")
print("Blue/green switch complete.")
if __name__ == "__main__":
main()
Notes and Suggestions
Labeling: Make sure your containers are labeled (color=blue, color=green, etc.). This script filters by app=mywebapp,color=blue to find “blue.”
Health Checks: Your image should define a HEALTHCHECK in the Dockerfile. For example:
The script waits until Docker reports the container as healthy.
Networking: The example assumes both your app containers and Nginx container (if any) are on a user-defined Docker network (myapp-net). In that setup, containers can reference each other by name, or you can inspect the IP as shown.
Nginx Configuration: The script writes a simple upstream file and reloads Nginx. You can adapt it to modify an existing config. For production, consider using symbolic links or templating.
Rollback: To roll back, you might keep the “blue” container around and only stop it after confirming “green” is serving correctly. For full rollback, you can reverse the labels or start a new container from the previous image.
This approach should give you a starting point for automating a blue/green deployment using the Docker Python SDK. Adjust labels, container names, port mapping, and Nginx config to match your specific environment.