Creating a Django Project in a Docker-Based Server Environment
Preparing the server and Docker environment
Cloud server setup
Before deploying or debugging a Django project online, prepare a cloud server with a public ip. The public address is needed so the project can be accessed from a browser during development and testing.
After the server is ready, configure password-free login from your local machine or any convenient shell terminal. This makes it easier to connect to the server at any time without repeatedly entering credentials.
Loading the Docker image and starting the container
Once the server environment is configured, upload the course-provided Docker image django_lesson_1_0.tar to the server from the terminal:
scp /var/lib/acwing/docker/images/django_lesson_1_0.tar server_name: #server_name 为配置好免密登录的服务器名称
Then load the image on the server:
docker load -i django_lesson_1_0.tar
Create and run a container, while also initializing the required port mappings:
docker run -p 20000:22 -p 8000:8000 --name django_server -itd django_lesson:1.0
A few details are worth noting:
- If a host port is already occupied by another container, change the mapping, for example to
20022:22. - If the container was created without the required port mapping, stop and remove it, then create it again.
- A single host port can only be used by one container. If a running container needs additional ports later, the current container must be packaged into an image and then started again with the new mappings.
After the container is running, connect to it and create a root user. Then configure password-free login for the container as well, so future operations can be done more conveniently.
Initializing the Django project and Git repository
Open tmux and create a new Django project:
django-admin startproject acapp #acapp 为项目所在文件夹
Enter the acapp project directory and initialize it as a git repository. This makes the project easier to maintain, supports version control, and helps avoid losing work after pushing it to a remote repository.
git init #进入 acapp 中初始化git仓库
Next, upload the container's public key to the Git hosting service by adding it as an ssh key in the account preferences. After that, create a new remote project and follow the instructions shown by the Git service to connect the local repository from the terminal.
Running the project for the first time
Inside the acapp directory, start the Django development server with:
python3 manage.py runserver 0.0.0.0:8000
Then open the project in a browser using:
xx.xx.xx.xx:8000
Here, xx.xx.xx.xx is the server's public ip, and 8000 is the exposed access port.
On the first visit, Django may report that the current ip needs to be added to ALLOWED-HOSTS. This setting is usually located in /acapp/acapp/settings.py. Open settings.py with vim, find ALLOWED-HOSTS, and add the server ip to it.
While editing the same file, locate the TIME_ZONE option and change it to 'Asia/Shanghai', so the project time matches the local time zone.
If the location of the setting is unclear, search the project directly:
ag ALLOWED-HOSTS
This will return the file path containing the configuration.
Keep these points in mind while the server is running:
- The console prints request information whenever the project homepage is accessed. Press
Ctrl + cto stop the process. - Some updated frontend-related files take effect while the server is running, and the console will also display related error messages if something goes wrong.
Creating a Django app
Create a Django sub-application with:
python3 manage.py startapp game #game 为该子应用的名字
The later development work for this project will mainly take place inside the game app directory.
Stop the running development server and synchronize the database:
python3 manage.py migrate
Create an administrator account:
python3 manage.py createsuperuser
Then restart the server:
pyhton3 manage.py runserver 0.0.0.0:8000
Open the admin page in the browser:
xx.xx.xx.xx:8000/admin
After the login page appears, enter the administrator account created in the previous step.
Understanding the project structure and request flow
Common Django app structure
A typical Django application usually contains the following parts:
models: stores data-related classes and predefinedclassdefinitions.views: stores functions and their execution logic.urls: stores routes and controls where links point.templates: storeshtmlfiles.
How the route and view logic works
game/views.py
The views file contains functions and the logic they execute:
from django.http import HttpResponse
def index(resquest):
return HttpResponse("lys is a dog")
In this example, when the index() function receives a user request, it is called and returns the result of HttpResponse("lys is a dog").
game/urls.py
The urls file stores route definitions. In this case, it defines the routes for the game sub-application:
from django.urls import path
from game.views import index # 从game/views.py 里面调用index函数
urlpatterns = [
path('', index, name="index")
]
The statement path('', index, name = 'game_index') means that when the user visits the /game directory of the site, the index function will be called. Since the route path is '', it represents an empty path, which points by default to the root of the current directory.
The definition and execution logic of index are stored in game/views.py, so from game.views import index is required. The name="index" part gives this route a name inside the current urls.py file.
acapp/urls.py
A sub-application route must also be included in the route configuration of the overall project:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('', include('game.urls')),
path('admin/', admin.site.urls)
]
Here, the first path also uses an empty route, meaning it points to the root of the entire website by default. Since the called function is include('game.urls'), visiting the project root effectively forwards the request to the route definitions inside game.urls.
Inside game/urls.py, the route has already been mapped to the target function. Therefore, after the project-level route includes game.urls, Django continues to execute the function specified there.
Putting the two route files together: when the browser visits xx.xx.xx.xx:8000/, the request is effectively directed to the game route. Then game/urls.py calls the index function in game/views.py, and that function returns the string "lys is a dog", which is displayed on the page.