Django Docker Setup



In this guide you will learn how to:

  • Create a Dockerfile file describing a simple Python container.
  • Build, run, and verify the functionality of a Django, Flask, or General Python app.
  • Debug the app running in a container.

Docker stop daemon docker rm docker rm daemon To remove all containers, we can use the following command: docker rm -f $(docker ps -aq) docker rm is the command to remove the container.-f flag (for rm) stops the container if it’s running (i.e., force deletion).-q flag (for ps) is to print only container IDs. Mar 09, 2021 Django is a high-level Python Web framework that encourages rapid development and clean pragmatic design. A Web framework is a set of components that provide a standard way to develop websites fast and easily. Django’s primary goal is to ease the creation of complex database-driven websites. This is a step-by-step tutorial that details how to configure Django to run on Docker with Postgres. For production environments, we'll add on Nginx and Gunicorn. We'll also take a look at how to serve Django static and media files via Nginx. Dependencies: Django v3.0.7; Docker v19.03.8; Python v3.8.3; Django on Docker Series. Docker can be used for more than that. It’s a containerization tool for spinning up isolated, reproducible application environments. You can read Django Development with Docker Compose and Machine if you want to learn how to containerize your Django project.

Docker Django Setup

Prerequisites

  • Docker Desktop and the VS Code Docker extension must be installed as described in the overview.
  • For Python development, complete all Getting started with Python steps
  • A runnable Python application

Create a Python project

If you don't have a Python project already, follow these commands sequentially from the terminal:

If you want to containerize a complete Django or Flask web app, you can use one of the following samples:

  • python-sample-vscode-django-tutorial, which is the result of following the Django Tutorial

  • python-sample-vscode-flask-tutorial, which is the result of following the Flask Tutorial

After verifying your app runs properly, you can now Dockerize your application.

Add Docker files to the project

  1. Open the project folder in VS Code.

  2. Open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and use the Docker: Add Docker Files to Workspace... command:

  3. When the prompt appears, select Python: Django, Python: Flask, or Python: General as the app type. For this tutorial, we will select Python: Django.

  4. Select either Yes or No when prompted to include Docker Compose files. If you select Yes, you will need to verify the path to your wsgi.py file in the Dockerfile to run the Compose Up command successfully. Compose is typically used when running multiple containers at once.

  5. Enter the relative path to the app's entry point. This excludes the workspace folder you start from. According to official Django documentation, this path is commonly manage.py (root folder) or subfolder_name/manage.py. According to official Flask documentation, this is the path to where you create your Flask instance.

    Tip: You may also enter the path to a folder name as long as this folder includes a __main__.py file.

  6. If Python: Django or Python: Flask was selected, specify app port for local development. Django defaults to port 8000, while Flask defaults to port 5000; however, any unused port will work. We recommend selecting port 1024 or above to mitigate security concerns from running as a root user.

  7. With all of this information, the Docker extension creates the following files:

    • A Dockerfile. To learn more about IntelliSense in this file, refer to the overview.

    • A .dockerignore file to reduce the image size by excluding files and folders that aren't needed such as .git, .vscode, and __pycache__.

    • If Docker Compose was selected, a docker-compose.yml and docker-compose.debug.yml file.

    • If one does not already exist, a requirements.txt file for capturing all app dependencies.

    Important note: To use our setup, the Python framework (Django/Flask) and Gunicorn must be included in the requirements.txt file. If the virtual environment/host machine already has these prerequisites installed and is supposed to be identical to the container environment, ensure app dependencies are ported over by running pip freeze > requirements.txt in the terminal. This will overwrite your current requirements.txt file.

Add an environment variable to the image

The Docker Extension helps you author Dockerfiles by using IntelliSense to provide auto-completions and contextual help. To see this feature in action:

  1. Open the Dockerfile.

  2. Underneath the EXPOSE statement, type ⌃Space (Windows, Linux Ctrl+Space) to trigger IntelliSense and scroll to ENV.

  3. Press Tab or Enter to complete the statement, then set the key to VAR1 and the value to 10.

Gunicorn modifications for Django/Flask apps

To give Python Web Developers a great starting point, we chose to use Gunicorn as the default web server. Since it is referenced in the default Dockerfile, it is included as a dependency in the requirements.txt file.

Note: To use Gunicorn as your web server, it must be included in the requirements.txt file as an app dependency. It does not need to be installed in your virtual environment/host machine. The Gunicorn entry point is overridden locally if your app is run with Python: Django or Python: Flask.

Django apps

To use Gunicorn, it must bind to an application callable (what the application server uses to communicate with your code) as an entry point. This callable is declared in the wsgi.py file of a Django application. To accomplish this binding, the final line in the Dockerfile says:

If your project does not follow Django's default project structure (that is, a workspace folder and a wsgi.py file within a subfolder named the same as the workspace) you must overwrite the Gunicorn entry point in the Dockerfile to locate the correct wsgi.py file.

Tip: If your wsgi.py file is in the root folder, the final argument in the command above will be 'wsgi'. Within subfolders, the argument would be 'subfolder1_name.subfolder2_name.wsgi'.

Django Docker Setup Commands

Flask apps

To use Gunicorn, it must bind to an application callable (what the application server uses to communicate with your code) as an entry point. This callable corresponds with the file location and variable name of your created Flask instance. According to official Flask Documentation, users generally create a Flask instance in the main module or in the __init__.py file of their package in this manner:

To accomplish this binding, the final line in the Dockerfile says:

During the Docker: Add Docker Files to Workspace... command, you configure the path to the Flask instance, however, the Docker extension assumes your Flask instance variable is named app. If this is not the case, you must change the variable name in the Dockerfile.

Tip: If your main module was in the root folder as a file named main.py and had a Flask instance variable was named myapp, the final argument in the command above will be 'main:myapp'. Within subfolders, the argument would be 'subfolder1_name.subfolder2_name.main:myapp'.

Build, run, and debug the container

The Docker: Add Docker Files to Workspace... command automatically creates a Docker launch configuration to build and run your container in debug mode. To debug your Python app container:

  1. Navigate to the manage.py file and set a breakpoint on this line:

    Note: If you have created an app project as shown in the Create a Django app section of the Django tutorial, you can also set a breakpoint in views.py or wherever you choose.

  2. Navigate to Run and Debug and select Docker: Python - Django.

  3. Start debugging using the F5 key.

    • The Docker image builds.
    • The Docker container runs.
    • The python debugger stops at the breakpoint in manage.py.
  4. Step over this line once.

  5. Navigate to the Debug Console and type os.environ['DJANGO_SETTINGS_MODULE']

  6. Once you view the output, press continue.

The Docker extension will launch your browser to a randomly mapped port:

Tip: To modify your Docker build settings, such as changing the image tag, navigate to .vscode -> tasks.json under the dockerBuild attribute in the docker-build task. Use IntelliSense within the file (⌃Space (Windows, Linux Ctrl+Space)) to display all other valid directives.

Django

Use the Docker Explorer

The Docker Explorer provides an interactive experience to examine and manage Docker assets such as containers, images, and so on. To see an example:

  1. Navigate to the Docker Explorer.

  2. In the Containers tab, right-click on your container and choose View Logs.

  3. The output will be displayed in the terminal.

Next steps

You're done! Now that your container is ready, you may want to:

There are 3 main things to do:

  • set STATIC_ROOT in settings.py
  • run python2.7 manage.py collectstatic (or python3.5 or python3.6 as appropriate)
  • set up a Static Files entry on the PythonAnywhere Web tab.

Optionally, you can also customise STATIC_URL, if you want to use a static URL prefix other than /static/

Set STATIC_ROOT in settings.py

The STATIC_ROOT variable in settings.py defines the single folder you wantto collect all your static files into. Typically, this would be a top-levelfolder inside your project, eg:

The important thing is this needs to be the full, absolute path to your static files folder.

Run pythonX.Y manage.py collectstatic

This command (don't forget to replace 'X.Y' with the version of Python yourwebsite uses) collects up all your static files from each of your app folders(including the static files for the admin app) and from any other folders youspecify in settings.py, and copies them into STATIC_ROOT.

Django Docker Setup Software

You need to re-run this command whenever you want to publish new versions ofyour static files.

(Optionally) change STATIC_URL

If you really must, you can change the default STATIC_URL, which is /static/,to being a different prefix, like /assets/, or whatever it may be. You'llprobably want to use the {% static %} template tag with this. There's moreinfo in the djangodocs.

Set up a static files mapping

Django Docker Setup Command

Django docker settings.py

Finally, set up a static files mapping to get our web servers to serve out your static files for you.

  • Go to the Web tab on the PythonAnywhere dashboard
  • Go to the Static Files section
  • Enter the same URL as STATIC_URL in the url section (typically, /static/)
  • Enter the path from STATIC_ROOT into the path section (the full path, including /home/username/etc)

Django Docker Setup Download

Then hit Reload and test your static file mapping by going to retrieve a known static file.

Django Docker Setup Free

Eg, if you have a file at /home/myusername/myproject/static/css/base.css, go visit http://www.your-domain.com/static/css/base.css

Serving static files in development

Django does have an alternative for serving static files during development,which can avoid the need for you to run collectstatic whenever you makechanges to your files, but it comes at the cost of putting an extra processingburden on the Python parts of your app. If you really want to use this, you'llfind more info in the djangodocs.

Media files

If you're using Django's default uploaded fileshandling, then you'llneed to set up a similar static files mapping from MEDIA_URL toMEDIA_ROOT...