天天看點

使用docker-compose部署Django項目

先從最基本的功能開始

在一切工作開始前,需要先編輯好三個必要的檔案。

第一步,因為應用将要運作在一個滿足所有環境依賴的 Docker 容器裡面,那麼我們可以通過編輯

Dockerfile

檔案來指定 Docker 容器要安裝内容。内容如下:

FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
COPY . /code/
           

以上内容指定應用将使用安裝了 Python 以及必要依賴包的鏡像。更多關于如何編寫

Dockerfile

檔案的資訊可以檢視 Dockerfile 使用。

第二步,在

requirements.txt

檔案裡面寫明需要安裝的具體依賴包名。

Django>=2.0,<3.0
psycopg2>=2.7,<3.0
           

第三步,

docker-compose.yml

檔案将把所有的東西關聯起來。它描述了應用的構成(一個 web 服務和一個資料庫)、使用的 Docker 鏡像、鏡像之間的連接配接、挂載到容器的卷,以及服務開放的端口。

version: "3"
services:
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
           

現在我們就可以使用

docker-compose run

指令啟動一個

Django

應用了。

docker-compose run web django-admin startproject django_example .
           

由于 web 服務所使用的鏡像并不存在,是以 Compose 會首先使用

Dockerfile

為 web 服務建構一個鏡像,接着使用這個鏡像在容器裡運作

django-admin startproject django_example

指令。

這将在目前目錄生成一個

Django

應用。

ls
Dockerfile       docker-compose.yml          django_example       manage.py       requirements.txt
           

如果你的系統是 Linux,記得更改檔案權限。

$ sudo chown -R $USER:$USER .
           

首先,我們要為應用設定好通路位址。用以下内容替換

django_example/settings.py

檔案中

ALLOWED_HOSTS= ...

定義的節點内容。

ALLOWED_HOSTS = ["192.168.75.21"]
           
# docker-compose up
django_db_1 is up-to-date
Creating django_web_1 ...
Creating django_web_1 ... done
Attaching to django_db_1, django_web_1
db_1   | The files belonging to this database system will be owned by user "postgres".
db_1   | This user must also own the server process.
db_1   |
db_1   | The database cluster will be initialized with locale "en_US.utf8".
db_1   | The default database encoding has accordingly been set to "UTF8".
db_1   | The default text search configuration will be set to "english".
web_1  | Performing system checks...
web_1  |
web_1  | System check identified no issues (0 silenced).
web_1  |
web_1  | November 23, 2017 - 06:21:19
web_1  | Django version 1.11.7, using settings 'django_example.settings'
web_1  | Starting development server at http://0.0.0.0:8000/
web_1  | Quit the server with CONTROL-C.