This hands-on guide walks you through setting up a production-like environment for a Django web application using Docker containers for the web server (Gunicorn), reverse proxy (Nginx), and database (PostgreSQL).
Before you begin, ensure you have the following installed and configured:
docker
commands, Docker Compose is the standard tool for managing multi-container applications and is highly recommended for production. (We'll stick to basic commands here for clarity, but note where Compose would simplify things).pyenv
We start by setting up a clean and isolated Python environment on your host machine using pyenv
. This is good practice for local development and helps ensure you can install the specific Python version and libraries needed before transferring them into the Docker image.
Install system build dependencies
*pyenv
builds Python versions from source code. These packages provide the necessary compilers, libraries, and headers required for a successful Python build on Linux.*sudo apt-get update
sudo apt-get install -y \\
make build-essential libssl-dev zlib1g-dev \\
libreadline-dev libsqlite3-dev wget curl llvm \\
libncursesw5-dev xz-utils tk-dev libxml2-dev \\
libxmlsec1-dev libffi-dev liblzma-dev
Install pyenv
pyenv
installer script. It clones the pyenv
repository and sets up its basic structure in your home directory. The following commands add pyenv
to your shell's PATH and initialize it, allowing you to use the pyenv
command.curl <https://pyenv.run> | bash
# Add to your shell init (~/.bashrc or ~/.zshrc):
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
# Apply changes:
source ~/.bashrc
(Note: You might need to close and reopen your terminal or run source ~/.bashrc
or source ~/.zshrc
for pyenv
to be available.)
Create & activate a Python 3.11.6 virtualenv
*pyenv install 3.11.6
downloads and compiles the specified Python version. pyenv virtualenv 3.11.6 py3_11_6
creates a virtual environment named py3_11_6
based on that Python version. pyenv activate py3_11_6
switches your current shell session to use this virtual environment, isolating installed libraries.*pyenv install --list # see available versions
pyenv install 3.11.6
pyenv virtualenv 3.11.6 py3_11_6
pyenv activate py3_11_6
Install Python libraries
django
is the web framework, gunicorn
is a production-ready Python WSGI HTTP Server (used later in Docker), psycopg2-binary
is the PostgreSQL adapter for Python, and pyyaml
is often used for configuration files, though not strictly necessary for this basic example it's a common dependency.pip install django gunicorn psycopg2-binary pyyaml
Deactivate when done
pyenv deactivate
Now, we'll create a basic Django project within the prepared Python environment.