LoginSignup
9
6

More than 1 year has passed since last update.

DockerでVue(Vite使用)の環境構築をしたが、docker-compose upをしてもVueの画面が表示されない時の対処法

Posted at

1. 問題

DockerでViteを使ってVueの環境構築をしたが、localhost:5173を叩いてみてもVueの初期画面が表示されなかった。

スクリーンショット 2023-01-15 17.10.23.png

設定したDockerfileとdocker-compose.ymlは以下の通り。
ポート番号等は特に間違っていなさそう。

Dockerfile
FROM node:18.13.0-alpine

ARG WORKDIR

ENV HOME=/${WORKDIR}

WORKDIR ${HOME}

RUN apk update && npm install -g npm

CMD ["npm", "run", "dev"]
docker-compose.yml
version: '3.8'

services:
 db:
  ・・・

 backend:
  ・・・

 frontend:
    build:
      context: ./frontend
      
      args:
        WORKDIR: $WORKDIR
    
    volumes:
      - './frontend:/$WORKDIR'
    # ホストの5173番ポートをコンテナの5173番ポートに繋ぐ
    ports:
      - '5173:5173'
    
    depends_on:
      - backend

2. 解決法

エラー

ログを見ると、networkの箇所に何やら表示されている
Network: use --host to expose

frontend_1  | 8:09:42 AM [vite] vite.config.js changed, restarting server...
frontend_1  | 8:09:43 AM [vite] server restarted.
frontend_1  | 
frontend_1  |   ➜  Local:   http://localhost:5173/
frontend_1  |   ➜  Network: use --host to expose

解決法

下記のGitHubに解決法が2つ載っていた

The default host now listens to 127.0.0.1 so you only get localhost exposure. It was changed because it is a security concern to expose your file system to external addresses by default.
To get the same behaviour as in v2.2, you can use:
vite --host
Or set server.host to true in your config.
https://vitejs.dev/config/#server-host

npm run devする時に、--hostオプションを付ける

npm run dev -- --host

②configファイルにhostからアクセスできるよう設定する

server: {
  host: true
}

今回は②で対応する

vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  //ここを追加!
  server: {
    host: true
  },

  plugins: [vue()]
})

上記を追加するとNetworkが変更されたことが分かる

frontend_1  | 
frontend_1  |   VITE v4.0.4  ready in 1665 ms
frontend_1  | 
frontend_1  |   ➜  Local:   http://localhost:5173/
frontend_1  |   ➜  Network: http://172.21.0.4:5173/

アクセスできるようになった!!!
スクリーンショット 2023-01-15 18.00.51.png

3. 背景

この設定が必要になった背景は以下。

デフォルトのホスト(コンテナ側)はポート番号127.0.0.1をリッスンするようになったので、自ホスト以外からのリクエストが拒否されてしまう。これはデフォルトでファイルシステムを外部のアドレスに公開することはセキュリティ上問題があるためこのようになっている。

何の設定もしていない場合、外部アドレス(ホスト)からアクセスすることができないので、ホスト側からアクセス可能とするには、上記の設定が必要。

参考

9
6
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
9
6