It's always been a challenge for Django developers to find the easiest and most efficient way to dockerize their applications. In this article we will acknowledge this challenge and come up with a viable solution.
First of all, you want to head over to the official Docker website and download docker desktop for your operating system:
Once you have downloaded docker desktop. You can proceed to start it up. Once it has started you can go ahead and explore the menu's/sections on the left, such as:
- Dev environments
We will only be focusing on Containers and Images. So, once we build our docker image it will appear under the Images section, and if we run our docker container it will appear under the Containers section.
Next we will need to install Gunicorn:
Gunicorn is a WSGI HTTP server that is necessary to help us to dockerize our Django web app.
The next step involves generating a requirements.txt file.
To generate a requirements.txt file simply head over to your terminal and enter in the following command:
pip freeze > requirements.txt
The next step involves creating our Dockerfile.py file within our application:
# We need to import a python based image
# Create a working directory for our docker file
# Sends python output to our container logs
# Copy all of the packages that are within our requirements.txt file
COPY requirements.txt requirements.txt
# Install all of the packages that are within our requirements.txt file
RUN pip3 install -r requirements.txt
# Copy our entire project directory for our docker image
COPY . .
# To run our Django app we need to serve it with Gunicorn
# Please note: elevate is the name of my Django project
CMD gunicorn elevate.wsgi:application --bind 0.0.0.0:8000
# Expose our docker image at port 8000
Next we will need to create a docker-compose.yml file to help us to define our container.
version: "3.8" # We need to define the docker specification version
services: # Define our service(s) - in this case we only have one
app: # We will build a singular app
build: . # Used to build our dockerfile
volumes: # This refers to our directory that we defined /djangoapp
ports: # We want to expose port 8000 within our container
image: myapp:django # Tag/add our docker image name
container_name: djangoapp_container # Specify a container name
command: gunicorn simply.wsgi:application --bind 0.0.0.0:8000 # Expose all IP addresses to connect to port 8000
To build our docker image we need to run the following command within our terminal:
To run our docker container we need to run the following command within our terminal: