Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A production ready example Django app that's using Docker and Docker Compose.

License

NotificationsYou must be signed in to change notification settings

nickjj/docker-django-example

Repository files navigation

You could use this example app as a base for your new project or as a guide toDockerize your existing Django app.

The example app is minimal but it wires up a number of things you might use ina real world Django app, but at the same time it's not loaded up with a millionpersonal opinions.

For the Docker bits, everything included is an accumulation ofDocker bestpracticesbased on building and deploying dozens of assorted Dockerized web apps sincelate 2014.

This app is using Django 5.2.3 and Python 3.13.5. The screenshot showsX.X.X since they get updated regularly:

Screenshot

🧾 Table of contents

🧬 Tech stack

If you don't like some of these choices that's no problem, you can swap themout for something else on your own.

Back-end

Front-end

But what about JavaScript?!

Picking a JS library is a very app specific decision because it depends onwhich library you like and it also depends on if your app is going to bemostly Django templates with sprinkles of JS or an API back-end.

This isn't an exhaustive list but here's a few reasonable choices depending onhow you're building your app:

On the bright side with esbuild being set up you can use any (or none) of thesesolutions very easily. You could follow a specific library's installationguides to get up and running in no time.

Personally I'm going to be using Hotwire Turbo + Stimulus in most newerprojects.

🍣 Notable opinions and extensions

Django is an opinionated framework and I've added a few extra opinions based onhaving Dockerized and deployed a number of Django projects. Here's a few (butnot all) note worthy additions and changes.

  • Packages and extensions:
  • Linting and formatting:
    • ruff is used to lint and format the code base
  • Django apps:
    • Addpages app to render a home page
    • Addup app to provide a few health check pages
  • Config:
    • Log to STDOUT so that Docker can consume and deal with log output
    • Extract a bunch of configuration settings into environment variables
    • Rename project directory from its custom name toconfig/
    • src/config/settings.py and the.env file handles configuration in all environments
  • Front-end assets:
    • assets/ contains all your CSS, JS, images, fonts, etc. and is managed by esbuild
    • Custom502.html andmaintenance.html pages
    • Generate favicons using modern best practices
  • Django defaults that are changed:
    • Use Redis as the default Cache back-end
    • Use signed cookies as the session back-end
    • public/ is the static directory where Django will serve static files from
    • public_collected/ is wherecollectstatic will write its files to

Besides the Django app itself:

  • uv is used for package management instead ofpip3 (builds on my machine are ~10x faster!)
  • Docker support has been added which would be any files having*docker* inits name
  • GitHub Actions have been set up

🚀 Running this app

You'll need to haveDocker installed.It's available on Windows, macOS and most distros of Linux. If you're new toDocker and want to learn it in detail check out theadditional resourceslinks near the bottom of this README.

You'll also need to enable Docker Compose v2 support if you're using DockerDesktop. On native Linux without Docker Desktop you caninstall it as a pluginto Docker. It's been generallyavailable for a while now and is stable. This project uses specificDockerCompose v2featuresthat only work with Docker Compose v2 2.20.2+.

If you're using Windows, it will be expected that you're following along insideofWSL or WSL2.That's because we're going to be running shell commands. You can always modifythese commands for PowerShell if you want.

Clone this repo anywhere you want and move into the directory:

git clone https://github.com/nickjj/docker-django-example hellodjangocd hellodjango# Optionally checkout a specific tag, such as: git checkout 0.11.0

Copy an example .env file because the real one is git ignored:

cp .env.example .env

Build everything:

The first time you run this it's going to take 5-10 minutes depending on yourinternet connection speed and computer's hardware specs. That's because it'sgoing to download a few Docker images and build the Python + Yarn dependencies.

docker compose up --build

Now that everything is built and running we can treat it like any other Djangoapp.

Did you receive adepends_on "Additional property required is not allowed"error? Please update to at least Docker Compose v2.20.2+ or Docker Desktop4.22.0+.

Did you receive an error about a port being in use? Chances are it's becausesomething on your machine is already running on port 8000. Check out the docsin the.env file for theDOCKER_WEB_PORT_FORWARD variable to fix this.

Did you receive a permission denied error? Chances are you're running nativeLinux and youruid:gid aren't1000:1000 (you can verify this by runningid). Check out the docs in the.env file to customize theUID andGIDvariables to fix this.

Setup the initial database:

# You can run this from a 2nd terminal../run manage migrate

We'll go over that./run script in a bit!

Check it out in a browser:

Visithttp://localhost:8000 in your favorite browser.

Linting the code base:

# You should get no output (that means everything is operational)../run lint

Formatting the code base:

# You should see that everything is unchanged (it's all already formatted)../run format

There's also a./run quality command to run the above commands together.

Running the test suite:

# You should see all passing tests. Warnings are typically ok../run managetest

Stopping everything:

# Stop the containers and remove a few Docker related resources associated to this project.docker compose down

You can start things up again withdocker compose up and unlike the firsttime it should only take seconds.

🔍 Files of interest

I recommend checking out most files and searching the code base forTODO:,but please review the.env andrun files before diving into the rest of thecode and customizing it. Also, you should hold off on changing anything untilwe cover how to customize this example app's name with an automated script(coming up next in the docs).

.env

This file is ignored from version control so it will never be commit. There's anumber of environment variables defined here that control certain options andbehavior of the application. Everything is documented there.

Feel free to add new variables as needed. This is where you should put all ofyour secrets as well as configuration that might change depending on yourenvironment (specific dev boxes, CI, production, etc.).

run

You can run./run to get a list of commands and each command hasdocumentation in therun file itself.

It's a shell script that has a number of functions defined to help you interactwith this project. It's basically aMakefile except withlesslimitations.For example as a shell script it allows us to pass any arguments to anotherprogram.

This comes in handy to run various Docker commands because sometimes thesecommands can be a bit long to type. Feel free to add as many conveniencefunctions as you want. This file's purpose is to make your experience better!

If you get tired of typing./run you can always create a shell alias withalias run=./run in your~/.bash_aliases or equivalent file. Then you'll beable to runrun instead of./run.

✨ Running a script to automate renaming the project

The app is namedhello right now but chances are your app will be a differentname. Since the app is already created we'll need to do a find / replace on afew variants of the string "hello" and update a few Docker related resources.

And by we I mean I created a zero dependency shell script that does all of theheavy lifting for you. All you have to do is run the script below.

Run the rename-project script included in this repo:

# The script takes 2 arguments.## The first one is the lower case version of your app's name, such as myapp or# my_app depending on your preference.## The second one is used for your app's module name. For example if you used# myapp or my_app for the first argument you would want to use MyApp here.bin/rename-project myapp MyApp

Thebin/rename-projectscriptis going to:

  • Remove any Docker resources for your current project
  • Perform a number of find / replace actions
  • Optionally initialize a new git repo for you

Afterwards you can delete this script because its only purpose is to assist inhelping you change this project's name without depending on any complicatedproject generator tools or 3rd party dependencies.

If you're not comfy running the script or it doesn't work for whatever reasonsyou cancheck itoutand perform the actions manually. It's mostly running a find / replace acrossfiles and then renaming a few directories and files.

Start and setup the project:

This won't take as long as before because Docker can re-use most things. We'llalso need to setup our database since a new one will be created for us byDocker.

docker compose up --build# Then in a 2nd terminal once it's up and ready../run manage migrate

Sanity check to make sure the tests still pass:

It's always a good idea to make sure things are in a working state beforeadding custom changes.

# You can run this from the same terminal as before../run quality./run managetest

If everything passes now you can optionallygit add -A && git commit -m "Initial commit" and start customizing your app. Alternatively you can waituntil you develop more of your app before committing anything. It's up to you!

Tying up a few loose ends:

You'll probably want to create a freshCHANGELOG.md file for your project. Ilike following the style guide athttps://keepachangelog.com/ but feel freeto use whichever style you prefer.

Since this project is MIT licensed you should keep my name and email address intheLICENSE file to adhere to that license's agreement, but you can also addyour name and email on a new line.

If you happen to base your app off this example app or write about any of thecode in this project it would be rad if you could credit this repo by linkingto it. If you want to reference me directly please link to my site athttps://nickjanetakis.com. You don't have to do this, but it would be verymuch appreciated!

🛠 Updating dependencies

You can run./run uv:outdated or./run yarn:outdated to get a list ofoutdated dependencies based on what you currently have installed. Once you'vefigured out what you want to update, go make those updates in yourpyproject.toml and / orpackage.json file.

Or, let's say you've customized your app and it's time to add a new dependency,either for Python or Node.

In development:

Option 1
  1. Directly editpyproject.toml orassets/package.json to add your package
  2. ./run deps:install or./run deps:install --no-build
    • The--no-build option will only write out a new lock file without re-building your image
Option 2
  1. Run./run uv add mypackage --no-sync orrun yarn add mypackage --no-lockfile which will update yourpyproject.toml orassets/package.json with the latest version of that package but not install it
  2. The same step as step 2 from option 1

Either option is fine, it's up to you based on what's more convenient at thetime. You can modify the above workflows for updating an existing package orremoving one as well.

You can also accessuv andyarn in Docker with./run uv and./run yarnafter you've upped the project.

In CI:

You'll want to rundocker compose build since it will use any existing lockfiles if they exist. You can also check out the complete CI test pipeline intherun fileunder theci:test function.

In production:

This is usually a non-issue since you'll be pulling down pre-built images froma Docker registry but if you decide to build your Docker images directly onyour server you could rundocker compose build as part of your deploypipeline which is similar to how it would work in CI.

🤝 See a way to improve something?

If you see anything that could be improved please open an issue or start a PR.Any help is much appreciated!

🌎 Additional resources

Now that you have your app ready to go, it's time to build something cool! Ifyou want to learn more about Docker, Django and deploying a Django app here's acouple of free and paid resources. There's Google too!

Learn more about Docker and Django

Official documentation

Courses / books

Deploy to production

I'm creating an in-depth course related to deploying Dockerized web apps. Ifyou want to get notified when it launches with a discount and potentially getfree videos while the course is being developed thensign up here to getnotified.

👀 About the author

I'm a self taught developer and have been freelancing for the last ~20 years.You can read about everything I've learned along the way on my site athttps://nickjanetakis.com.

There's hundreds ofblog posts and a coupleofvideo courses on web development anddeployment topics. I also have apodcastwhere I talk with folks about running web apps in production.


[8]ページ先頭

©2009-2025 Movatter.jp