This guide provides a step-by-step walkthrough of containerizing a simple Flask web application and placing it behind an Nginx reverse proxy using Docker. It also covers orchestrating this multi-container setup with Docker Compose.
Before starting, ensure you have the following:
sudo
(root) privileges. (Necessary for installing system packages and managing Docker.)pyenv
(for Python versions). (A tool for managing multiple Python versions and virtual environments, useful for preparing your local development environment before containerization.)We'll start by setting up a local Python environment using pyenv
and installing Flask for initial testing.
Activate your pyenv virtualenv:
pyenv
. We assume you have a Python 3.11.6 environment named py3_11_6
set up from a previous lab.)pyenv activate py3_11_6
Install Flask:
pip install flask
Verify Flask version:
python - <<EOF
from importlib.metadata import version
print("Flask version:", version("flask"))
EOF
Deactivate when done:
deactivate
Now, we'll create a simple "Hello World" Flask application and test it locally outside of Docker.
Create your project folder:
myapp
for your project and navigates into it.)mkdir myapp && cd myapp
Create main.py
:
app = Flask(__name__)
), a route (@app.route('/')
) that returns "hello world!" for the root URL, and configures the app to run on all network interfaces (host='0.0.0.0'
) on port 8001 when the script is executed directly.)# Create a file named main.py with the following content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'hello world!'
if __name__ == '__main__':
# Run the app, listening on all interfaces (0.0.0.0) on port 8001
app.run(host='0.0.0.0', port=8001)
Run locally:
(Activates the virtual environment where Flask was installed, then runs the main.py
script, starting the Flask development server.)
pyenv activate py3_11_6
python main.py
→ Visit http://127.0.0.1:8001
in your browser to confirm the "hello world!" message.
Stop the server with Ctrl+C
, then
deactivate