Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Packaging and Deployment — Deploying to Railway

Packaging and Deployment — Deploying to Railway

In this chapter you will learn to configure the production environment and deploy the Django blog application to Railway to get a public access link.


Production environment configuration

In the development environment DEBUG=True, and Django displays detailed error information and debug pages.

In the production environment you must turn off DEBUG and configure security options correctly.

settings.py production configuration

Example

File path: blog_project/settings.py

import

os

The security key is read from environment variables (do not hard-code it in the code)

SECRET_KEY

=

os

.

environ

.

get

(

'SECRET_KEY'

,

'default development key'

)

DEBUG is controlled by environment variables

DEBUG

=

os

.

environ

.

get

(

'DEBUG'

,

'True'

)

.

lower

(

)

==

'true'

Allowed host names

ALLOWED_HOSTS

=

os

.

environ

.

get

(

'ALLOWED_HOSTS'

,

'127.0.0.1,localhost'

)

.

split

(

','

)

Static file collection directory

STATIC_ROOT

=

os

.

path

.

join

(

BASE_DIR

,

'staticfiles'

)

 

staticfiles/ in the project root directory

STATIC_URL

=

'/static/'

SECRET_KEY is Django's most important security key, used to encrypt session, CSRF token, etc. It must never be hard-coded in code or committed to Git. In production it is injected through environment variables.


Dependency management and requirements.txt

Generate a dependency list, which the deployment platform uses to install the packages required by the project.



(venv) $ pip freeze > requirements.txt

Check the file contents to ensure the following key dependencies are included:



Django>=5.0,<6.0

gunicorn>=21.0              # 生产级 WSGI 服务器

whitenoise>=6.0             # 静态文件服务(可选)

If gunicorn is not installed, install it first:



(venv) $ pip install gunicorn

(venv) $ pip freeze > requirements.txt


Configure Gunicorn + Whitenoise

Django's built-in runserver is not suitable for production.

Gunicorn is a production-grade Python WSGI server that handles concurrent requests.

Whitenoise lets Gunicorn serve static files directly (CSS, JS, images).

Example

File path: blog_project/settings.py

The Whitenoise middleware must be placed after SecurityMiddleware and before other middleware

MIDDLEWARE

=

[

   

'django.middleware.security.SecurityMiddleware'

,

   

'whitenoise.middleware.WhiteNoiseMiddleware'

,

 

New: static file middleware

   

'django.contrib.sessions.middleware.SessionMiddleware'

,

   

'django.middleware.common.CommonMiddleware'

,

   

'django.middleware.csrf.CsrfViewMiddleware'

,

   

'django.contrib.auth.middleware.AuthenticationMiddleware'

,

   

'django.contrib.messages.middleware.MessageMiddleware'

,

   

'django.middleware.clickjacking.XFrameOptionsMiddleware'

,

]

Create in the project root directory Procfile, telling Railway how to start the application:



web: gunicorn blog_project.wsgi --log-file -


Collect static files

In production, Django does not serve static files automatically; you need to use collectstatic to collect them into a unified directory.



(venv) $ python manage.py collectstatic

This command copies the static files of the Admin backend and the blog app to the STATIC_ROOT directory (staticfiles/).

In the development environment you generally do not need to run collectstatic (Django automatically finds each App's static directory). But before deployment you must run it to ensure all static files are concentrated in one directory for the web server to use.


Push the Project to GitHub

Create .gitignore

Ensure sensitive files and temporary files are not committed:



venv/

__pycache__/

*.pyc

db.sqlite3

staticfiles/

.env

Push to GitHub



$ git init

$ git add .

$ git commit -m "初始化 Django 博客项目"

$ git branch -M main

$ git remote add origin https://github.com/你的用户名/django-blog.git

$ git push -u origin main


Railway Deployment

Railway is an emerging cloud deployment platform with good support for full-stack applications like Django.

Deployment Steps

  1. Access the railway.app, log in with your GitHub account
  2. Click "New Project" → "Deploy from GitHub repo" → select the django-blog repository
  3. Railway automatically detects the Procfile and identifies the start command
  4. Set environment variables in Variables
  5. Click Deploy and wait for the build and deployment to complete

Environment variable configuration

Variable Name Value Description
SECRET_KEY A randomly generated long string Django secret key
DEBUG False Turn off debug mode
ALLOWED_HOSTS .railway.app Allow Railway domain access

Quickly generate a SECRET_KEY:



$ python -c "import secrets; print(secrets.token_urlsafe(50))"

After a successful deployment, you get a link like:https://django-blog.up.railway.app

Railway's free quota is limited ($5 or 500 hours per month). If you are just testing and learning, remember to pause the project when you are done. Heroku has cancelled its free plan, so this tutorial recommends Railway as an alternative.


Next Learning Directions

Learning Direction Who It's For Recommended Starting Point
Django REST Framework (DRF) Need to build an API backend for a frontend framework (Vue3/React) Learn Serializer + ViewSet and transform the blog into an API service
PostgreSQL Need a production-grade database Replace SQLite and use django-environ to manage database configuration
Celery asynchronous tasks Need background tasks (sending emails, generating reports) Integrate Redis + Celery to implement an asynchronous task queue
Django + Vue3/React frontend-backend separation Want a frontend-backend separated architecture Use DRF to build the API backend, Vue3/React to build the frontend, communicating via fetch

Chapter Summary

In this chapter you completed the final step: configuring the production environment (SECRET_KEY/DEBUG/ALLOWED_HOSTS), generating requirements.txt, configuring Gunicorn + Procfile, pushing to GitHub, and deploying online with Railway's one-click deployment.