In a previous post I deployed a Flask app with Docker. This time around I wanted to see if it was any different to host a Django app. It turns out that it wasn’t that much different.
First, install the Docker using their installation instructions for you platform. I am on a mac, so I installed the DMG from their site, and then from the command line ran,
brew install docker
The Docker daemon doesn’t start automatically after downloading it, so you need to find it, and double-click on it to start it up. Once it’s running, you can execute docker commands from the command line.
Create and cd into a directory called
mkdir example cd example
Start a Virtual Environment on your Host
Creating a virtual environment for your application will help you install and import only what is needed for your application. Once it is time to deploy, just freeze your requirements into a
requirements.txt document, and you’ll have a snapshot of what your application needs in order to run.
If you’re using Python3, from the
example/ directory you can say,
python3 -m venv venv source venv/bin/activate
Now you should see a
venv/ directory inside your
example/ directory. Now install Django by saying,
python -m pip install django
Once that is done, create a requirements document,
pip freeze > requirements.txt
This should create
requirements.txt at the root of the
Creating a Simple Django App
I used Django’s
startproject command to get started. This creates a directory for your project called
app/, with another directory inside that is also called
app/. The outer
app/ directory isn’t used anywhere internally, so you can name it whatever you like.
django-admin startproject app
Create a Dockerfile
I created a Dockerfile to install the requirements, copy the application over, and start the server. Note, I am currently in a directory called “example”. My
Dockerfile is in the root of that directory. The
app/ directory, containing my Flask app,
app.py, is also in the “example” directory, beside the
# ~/example/Dockerfile FROM python:3.7.0-alpine3.8 WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY app/* ./ EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]
Build and Run Docker
Now, we should be able to build an image by saying:
docker build -t hello-world
And then we should be able to run that image in a container by saying:
docker run -p 8000:8000 hello-world
Now, if we visit
localhost:8000 we should see the default Django splash page.