docker start a web container
Step 1: Setup
Define the application dependencies.
-
Create a directory for the project:
mkdir web cd web
-
Create a file called
app.py
in your project directory and paste this in:import time import redis from flask import Flask app = Flask(__name__) cache = redis.Redis(host='redis', port=6379) def get_hit_count(): retries = 5 while True: try: return cache.incr('hits') except redis.exceptions.ConnectionError as exc: if retries == 0: raise exc retries -= 1 time.sleep(0.5) @app.route('/') def hello(): count = get_hit_count() return 'Hello World! I have been seen {} times.\n'.format(count)
-
Create another file called
requirements.txt
in your project directory and paste this in:flask redis
Step 2: Create a Dockerfile
In this step, you write a Dockerfile that builds a Docker image. The image contains all the dependencies the Python application requires, including Python itself.
In your project directory, create a file named Dockerfile
and paste the following:
# syntax=docker/dockerfile:1 FROM python:3.7-alpine WORKDIR /code ENV FLASK_APP=app.py ENV FLASK_RUN_HOST=0.0.0.0 RUN apk add --no-cache gcc musl-dev linux-headers COPY requirements.txt requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 COPY . . CMD ["flask", "run"]
Step 3: Define services in a Compose file
Create a file called docker-compose.yml
in your project directory and paste the following:
version: "3.9" services: web: build: . ports: - "8000:5000" redis: image: "redis:alpine"
Step 4: Build and run your app with Compose
From your project directory, start up your application by running docker compose up
.