LoginSignup
1
1

More than 3 years have passed since last update.

初学者がDockerを使ってdjango+gunicorn+Nginxの環境を構築する

Posted at

Dockerfileを作成

Dockerfile
FROM python:3

RUN apt-get update && apt-get install -y \
    nano
WORKDIR  /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt

RUN mkdir -p /var/run/gunicorn
# CMD ["gunicorn", "conf.wsgi", "--bind=unix:/var/run/gunicorn/gunicorn.sock"]

requirements.txtを作成

requirements.txt
Django==2.2.6
gunicorn

docker-compose.ymlを作成

docker-compose.yml
version: '3'

volumes:
  gunicorn:
    driver: local

services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: django
    ports:
      - '8000:8000'
    volumes:
      - './web:/code'
      - gunicorn:/var/run/gunicorn
    tty: true
    stdin_open: true

  nginx:
    image: nginx
    container_name: test_nginx
    ports:
      - '80:80'
    volumes:
      - './nginx/html:/usr/share/nginx/html'
      - './nginx/conf.d:/etc/nginx/conf.d'
      - gunicorn:/var/run/gunicorn
    depends_on:
      - web

ディレクトリを作る

構成
.
├── Dockerifle
├── requirements.txt
├── docker-compose.yml
├── nginx
│   └── conf.d    # gunicornの設定ファイルを格納するため
└── web           # djangoプロジェクトを格納するため

gunicornの設定ファイルを作成

構成
.
├── docker-compose.yml
├── Dockerifle
├── requirements.txt
├── nginx
│   └── conf.d
│       └── gunicorn.conf    # コレを作成
└── web       

gunicorn.confの中身はこのような感じです。

gunicorn.conf
upstream gunicorn-django {
    server unix:///var/run/gunicorn/gunicorn.sock;
}

server {
    listen 80;
    server_name localhost;

    location / {
        try_files $uri @gunicorn;
    }

    location @gunicorn {
        proxy_pass http://gunicorn-django;
    }
}

docker-composeでイメージをビルドし、コンテナを起動する

$ docker-compose up -d

$ docker-compose ps でコンテナが二つともUpになっていることを確認します。

djangoプロジェクトを作成

まずはdjangoコンテナに入ります。

$ docker-compose exec web bash

djangoプロジェクトを作成します。

$ django-admin startproject conf .

バインドマウントをしているので、ホストのwebフォルダの配下にもconfフォルダやmanage.pyが作成されていると思います。今回、アプリケーションの作成は割愛しますが、実際のアプリ開発はここで行うと便利かもしれません。

settings.pyを変更

先ほど作成したdjangoプロジェクト内にあるsettings.pyのALLOWED_HOSTSを変更します。とりあえずどんなサーバーアドレスからのアクセスも受理することにしますが、必要に応じて変更した方が良いような気がします。。。

settings.py
ALLOWED_HOSTS = ['*']

exitでコンテナから抜けます。

ここからは試行錯誤…

ここからは試行錯誤の結果なので、非効率なやり方になっていると思います。何卒、ご容赦ください。良いやり方があったら教えて頂けると嬉しい…。
|ω・`)チラ 


一旦、コンテナをダウンさせます。

$ docker-compose down

次にDockerfileに追記します。

Dockerfile
# 末尾に追加
CMD ["gunicorn", "conf.wsgi", "--bind=unix:/var/run/gunicorn/gunicorn.sock"]

再びDockerをupさせます。

$ docker-compose up --build -d

$ docker-compose psでコンテナがUpになっていることを確認したら、ブラウザからlocalhost:80にアクセスし、ロケットが飛び立っていることを確認します。
スクリーンショット 2021-02-23 11.43.02.png

うーん…ひとまず動きましたが、うまくいっている確証が持てていません…。
間違っているところがありましたら申し訳ありません!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1