Python

To add a health check in a docker-compose.yml file for a Python application, follow these steps:


Step 1: Create a Python Application

Create a simple Flask-based Python application (app.py) that runs a web server.

from flask import Flask

app = Flask(__name__)

@app.route('/health')
def health_check():
    return "OK", 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Step 2: Create a Dockerfile

A Dockerfile is needed to containerize the application.

# Use official Python image
FROM python:3.9

# Set the working directory
WORKDIR /app

# Copy application files
COPY app.py requirements.txt /app/

# Install dependencies
RUN pip install -r requirements.txt

# Expose port
EXPOSE 5000

# Command to run the application
CMD ["python", "app.py"]

In the same directory, create a requirements.txt file:


You can build image and use i another vm

docker build -t my-python-app:latest .

Step 3: Add Health Check in docker-compose.yml

Now, create a docker-compose.yml file and add the healthcheck section.

Health Check Explanation

  • test: Runs curl -f http://localhost:5000/health to check if the service responds with a 200 OK.

  • interval: Runs the health check every 30 seconds.

  • timeout: Health check fails if no response within 5 seconds.

  • retries: If it fails 3 times consecutively, the container is marked as unhealthy.

  • start_period: Waits 10 seconds before starting health checks.


Step 4: Build and Run Containers

Run the following commands:


Step 5: Check Health Status

Run:

Or list containers and check their health:

You should see a "(healthy)" status in the output.


Step 6: Simulate a Failing Health Check

Modify app.py to return a 500 error:

Rebuild and restart:

You'll see the container marked as "(unhealthy)".


This setup ensures your Python application is monitored inside Docker Compose! 🚀

Last updated