3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Django+Vue.js の開発環境を docker-compose で構築する(2)

Last updated at Posted at 2021-01-16

この記事は前回からの続きです

前回:Django+Vue.js の開発環境を docker-compose で構築する(1)

前回は、Vue のコンテナを立ち上げてプロジェクトを作成し、GitHub でのレポジトリ管理をフロントエンド(Vue)とバックエンド(Django)に分けました。

今回やりたいこと

今回は、nginx のリバースプロキシを設定し、Vue のスタート画面を見るところまでやっていきます。

手順

  1. Vue のプロジェクトをビルドする
  2. docker-compose.dev.yml を編集する
  3. app_nginx.conf を編集する

1. Vue のプロジェクトをビルドする

まずは Vue のプロジェクトをビルドします。まだなんにも作ってないけどね。

$ docker-compose -f docker-compose.dev.yml run vue npm run build

正しくビルドされれば、Vue のディレクトリに dist というディレクトリができます。

2. docker-compose.dev.yml を編集する

次に、コンテナの /frontend./src/frontend をマウントさせるように、docker-compose.dev.yml の nginx セクションを編集します。

docker-compose.dev.yml(抜粋)
nginx:
  image: nginx:1.17
  restart: unless-stopped
  container_name: nginx
  networks:
    - django_net
  ports:
    - "80:80"
  volumes:
    - ./nginx/conf:/etc/nginx/conf.d
    - ./nginx/uwsgi_params:/etc/nginx/uwsgi_params
    - ./static:/static
    - ./src/frontend:/frontend   # 追加
  depends_on:
    - python

3. app_nginx.conf を編集する

最後に、nginx を次のとおりに設定します。

./nginx/conf/app_nginx.conf
upstream django {
  ip_hash;
  server python:8001;  # uWSGI で Django と nginx とが通信するためのポート
  server vue:3000;     # Vue と nginx とが通信するためのポート  # 追加
}

server {
  listen      80;      # 待ち受けポート
  server_name 127.0.0.1;
  charset     utf-8;

  location /static {
    alias /static;
  }
  
  client_max_body_size 75M;

  location / {            # 追加
    root /frontend/dist;  # 追加
  }                       # 追加
  
  location /apiv1/ {                      # 追加
    uwsgi_pass  django;                   # 追加
    include     /etc/nginx/uwsgi_params;  # 追加
  }

  location /admin/ {                      # 追加
    uwsgi_pass  django;                   # 追加
    include     /etc/nginx/uwsgi_params;  # 追加
  }                                       # 追加
}                                         # 追加

server_tokens off;

要するに、

  • / へのアクセスは、/frontend/dist にルーティング
  • /static へのアクセスは、./static にルーティング
  • /apiv1/admin へのアクセスは、uwsgi 経由で Django にルーティング
    とします。

ちなみに、ngnix の待ち受けポートが 80 番になっているのは、私が Mac 上の VirtualBox で Ubuntu Server を動かしており、ホストの 8081 番とゲストの 80 番を接続しているからです。だから、Mac のブラウザで http://127.0.0.1:8081/ にアクセスすれば、開発中の画面が見られるってワケ。
関連:もう VirtualBox の設定で悩まない。そう、Vagrant ならね😏

動作確認

以上を設定し、コンテナを再起動してトップページにアクセスすると、無事に Vue のスタート画面を見ることができました。

スクリーンショット 2021-01-16 21.51.36.png

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?