🚀 In this guide, we'll create a containerized Python web application that displays a "Hello World" message. This tutorial works on Ubuntu/Debian-based Linux distros
Before we start, update and upgrade your system packages:
sudo apt update
sudo apt upgrade -yInstall Docker and other required dependencies:
sudo apt install ca-certificates curl gnupgsudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo tee /etc/apt/keyrings/docker.asc > /dev/null
sudo chmod a+r /etc/apt/keyrings/docker.ascecho "deb [signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/nullsudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-pluginVerify installation:
docker --versionStart and enable Docker:
sudo systemctl enable --now dockerCheck Docker status:
sudo systemctl status dockerUbuntu now uses the Docker Compose plugin instead of the standalone binary:
sudo apt install docker-compose-plugin -yVerify installation:
docker compose versionInstall Python Pip for dependencies:
sudo apt install python3-pip
python3 -m pip install --upgrade pipSet up the directory structure:
mkdir docker-projects
cd docker-projectsCreate the app.py file:
touch app.py
nano app.pyCopy & paste the following Python Flask app:
from flask import Flask
import redis
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
try:
return cache.incr('hits')
except redis.exceptions.ConnectionError:
return 1
@app.route('/')
def hello():
count = get_hit_count()
return f"Hello World! You have visited {count} times."
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)Save the file (CTRL + X, then Y).
Create the requirements.txt file:
touch requirements.txt
nano requirements.txtAdd dependencies inside requirements.txt:
Flask
redis
Save (CTRL + X, then Y).
Create a Dockerfile:
touch Dockerfile
nano DockerfilePaste the following Dockerfile configuration:
FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]Save (CTRL + X, then Y).
Create the docker-compose.yml file:
touch docker-compose.yml
nano docker-compose.ymlPaste the Docker Compose config:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
depends_on:
- redis
redis:
image: "redis:alpine"Save (CTRL + X, then Y). ⚠ YAML files are sensitive to indentation—validate them before running!
Ensure you're in the docker-projects directory:
cd docker-projectsStart the containers:
sudo docker-compose up --buildOpen a browser and go to http://localhost:5000.
You should see:
Hello World! You have visited 1 times.
Refreshing the page will increase the visitor count.
Shut down the containers when you're done:
sudo docker-compose down