docker-django-example

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 常用JavaScript包
软件类型 开源软件
地区 不详
投 递 者 沈宇定
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

An example Django + Docker app

CI

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 of Docker bestpracticesbased on building and deploying dozens of assorted Dockerized web apps sincelate 2014.

This app is using Django 3.2.8 and Python 3.10.0. The screenshot doesn't getupdated every time I bump the versions:

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 Jinja 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 Webpack being set up you can use any (or none) of thesesolutions very easily. You could follow a specific library's Webpackinstallation guides 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:
    • gunicorn for an app server in both development and production
    • whitenoise for serving static files
  • Linting and formatting:
    • flake8 is used to lint the code base
    • black is used to format the code base
  • Django apps:
    • Add pages app with a / page and /up health check endpoint
  • 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 to config/
    • 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 Webpack
    • Custom 502.html and maintenance.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 where collectstatic will write its files to

Besides the Django app itself:

  • Docker support has been added which would be any files having *docker* inits name
  • GitHub Actions have been set up
  • A requirements-lock.txt file has been introduced using pip3. Themanagement of this file is fully automated by the commands found in the runfile. We'll cover this in more detail when we talk about updatingdependencies.

Running this app

You'll need to have Docker 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 the additional resourceslinks near the bottom of this README.

If you're using Windows, it will be expected that you're following along insideof WSL 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 hellodjango
cd hellodjango

# Optionally checkout a specific tag, such as: git checkout 0.5.0

Copy a few example files because the real files are git ignored:

cp .env.example .env
cp docker-compose.override.yml.example docker-compose.override.yml

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 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 the DOCKER_WEB_PORT_FORWARD variable 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:

Visit http://localhost:8000 in your favorite browser.

Not seeing any CSS? That means Webpack is still compiling. Give ita few more seconds and reload. It should self resolve.

Linting the code base:

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

Formatting the code base:

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

Running the test suite:

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

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 with docker-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 for TODO:,but please review the .env and run 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 the run file itself.

It's a shell script that has a number of functions defined to help you interactwith this project. It's basically a Makefile except with lesslimitations.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 run run instead of ./run.

Running a script to automate renaming the project

The app is named hello 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

The bin/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 can check 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 flake8
./run black
./run manage test

If everything passes now you can optionally git 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 fresh CHANGELOG.md file for your project. Ilike following the style guide at https://keepachangelog.com/ but feel freeto use whichever style you prefer.

Since this project is MIT licensed you should keep my name and email address inthe LICENSE 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

Let's say you've customized your app and it's time to make a change to yourrequirements.txt or package.json file.

Without Docker you'd normally run pip3 install -r requirements.txt or yarn install. With Docker it's basically the same thing and since these commandsare in our Dockerfile we can get away with doing a docker-compose build butdon't run that just yet.

In development:

You can run ./run pip3: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 yourrequirements.txt and / or assets/package.json file.

Then to update your dependencies you can run ./run pip3:install or ./run yarn:install. That'll make sure any lock files get copied from Docker's image(thanks to volumes) into your code repo and now you can commit those files toversion control like usual.

You can check out therun file to seewhat these commands do in more detail.

As for the requirements' lock file, this ensures that the same exact versionsof every package you have (including dependencies of dependencies) get used thenext time you build the project. This file is the output of running pip3 freeze. You can check how it works by looking atbin/pip3-install.

You should never modify the lock files by hand. Add your top level Pythondependencies to requirements.txt and your top level JavaScript dependenciesto assets/package.json, then run the ./run command(s) mentioned earlier.

In CI:

You'll want to run docker-compose build since it will use any existing lockfiles if they exist. You can also check out the complete CI test pipeline inthe run fileunder the ci: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 run docker-compose build as part of your deploypipeline.

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 then sign 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 of blog posts and a coupleof video courses on web development anddeployment topics. I also have a podcastwhere I talk with folks about running web apps in production.

  • 文件目录结构: [root@docker docker_dbmonitor]# ls -lrt total 12 drwxr-xr-x. 2 root root 42 May 20 09:02 nginx drwxr-xr-x. 3 root root 18 May 20 17:44 db_monitor_vue -rw-r--r--. 1 root root

  • Django对标SpringMVC Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。 其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件

  • 上一章我们成功搭建了容器化的 Django 项目,用到的数据库为默认的 Sqlite。Sqlite 虽然简单易用,但是线上部署时通常会选择更高效、更可靠的数据库,比如 MySQL。 本章将在上一章的基础上,修改并构建 Docker + Django + MySQL 的容器项目。 Docker-compose 我们在学习面向对象的编程语言时,会想方设法把功能独立的模块给独立出来,方便复用和维护。 容

  • 环境 windows 10家庭版(也就意味着要使用virtual box) docker容器上需要做的事情 在容器上新建一个django项目。这个就不讲了 在settings.py 添加ALLOWED_HOSTS=['*'] , 意味着允许 任何IP访问 将这个容器保存为一个image 运行这个容器 将容器的端口映射到虚拟机(docker-machine,也就是virtual box)的端口.运行

  • 其中,包括了主要的生产环境模块, 从alpine作起,镜像不大。保存用。 FROM alpine:3.7 COPY . /target-dir WORKDIR /target-dir RUN sed -i 's/dl-cdn.alpinelinux.org/mirror.tuna.tsinghua.edu.cn/g' /etc/apk/repositories &&\ apk add -

  • django项目建立教程见Django实现算法web服务_Mugo_Moon的博客-CSDN博客 1、生成依赖包文件requirements.txt (1)全局环境依赖全部生成(或单虚拟环境) pip freeze > requirements.txt (2)只生成项目依赖(pipreqs,github地址为:https://github.com/bndr/pipreqs) # pipreqs安装

 相关资料
  • Deploy Django using Nginx, Celery, Redis and Postgresql with Docker A boilerplate to deploy Django with cool stuff. Also serves as an example project from these tutorial: Deploy Django, Gunicorn, NGIN

  • Dockerizing Django with Postgres, Gunicorn, and Nginx Want to learn how to build this? Check out the post. Want to use this project? Development Uses the default Django development server. Rename .env

  • 我正在尝试更新我的docker映像从Python:3.8.2-alpine3.10切换到Python:3.9.0-alpine3.12,但在运行django命令ssl_check_private_key:symbol not found时遇到了一个问题。 运行检查时出现以下错误: bash-c“touch/var/donor_reporting_portal/.touch&&django-admi

  • 当我运行容器时,它就挂在下一行上,如果我写 curl http://0.0.0.0:8000/ 我得到了 无法连接到0.0.0.0端口8000:连接拒绝 顺便说一句,如果我用myapp图像运行docker ps,我会得到这样的结果: 当我使用django-compose.yml和部署服务时,我得到了以下信息:

  • 我无法通过集装箱中的港口连接到django。我使用的地址是:0.0.0.0.:8000,请参阅:http://joxi.ru/Dr8MeGLhkBWnLm.我正在用一个命令创建一个图像和一个容器:“docker compose up-d”。 docker-compose.yaml Dockerfile 如何解决此问题?

  • 问题内容: 我想在一个简单的Docker容器中运行Django。 首先,我使用Docker-file构建了我的容器。没有什么特别的(只有FROM,RUN和COPY命令) 然后我用命令运行容器 输入我的容器: 运行Django服务器: 得到了: 但是当我转到127.0.0.1:8000时,我什么也看不到: 没有Nginx或其他工作服务器。 我究竟做错了什么? 更新1(Dockerfile) 问题答案