LoginSignup
15
16

More than 3 years have passed since last update.

VueアプリケーションをDockerのNginx上で公開する

Posted at

概要

Vue CLIのドキュメントに記載の内容ほぼそのままですが
VueアプリケーションをNginx上で公開する方法です。
https://cli.vuejs.org/guide/deployment.html#docker-nginx

フォルダ構成

最終的なフォルダ構成は以下のようになります。

.
├── docker-compose.yaml
└── nginx
    ├── Dockerfile
    ├── app
    │   └── vue-app
    ├── .dockerignore
    └── nginx.conf

Vueアプリケーションの作成

まずは公開するVueアプリケーションを作成します。
今回はパッケージマネージャをYarnに設定して、その他はデフォルトで作成しています。

$ mkdir -p nginx/app
$ cd nginx/app
$ vue create vue-app

作成が完了したところで一度サーバーを起動して確認してみます。

$ cd vue-app
$ yarn serve

以下のURLを開いてVueアプリケーションが表示されていればOKです。
http://localhost:8081/

Docker上での立ち上げ

次にDocker上で立ち上げるために以下のファイルを作成していきます。
作成する場所はフォルダ構成を参考にしてください。

docker-compose.yaml
version: '3'
services:
  nginx:
    build: ./nginx
    ports:
      - "8080:80"

yarn installでキャッシュを利用するために、
先にpackage.jsonとyarn.lockをコピーしてインストールを行っています。

Dockerfile
FROM node:14.0.0-alpine3.11 as build-stage

WORKDIR /app
COPY app/vue-app/package*.json ./
COPY app/vue-app/yarn.lock ./
RUN yarn install
COPY app/vue-app/ ./
RUN yarn run build

FROM nginx:1.17.10-alpine as production-stage

RUN mkdir /app
COPY --from=build-stage /app/dist /app
COPY nginx.conf /etc/nginx/nginx.conf

ローカルのnode_modulesとdistをDockerと干渉させないためにignoreに追加します。

.dockerignore
**/node_modules
**/dist

ここはドキュメントの内容そのまま。

nginx.conf
user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
  worker_connections  1024;
}
http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log  /var/log/nginx/access.log  main;
  sendfile        on;
  keepalive_timeout  65;
  server {
    listen       80;
    server_name  localhost;
    location / {
      root   /app;
      index  index.html;
      try_files $uri $uri/ /index.html;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }
}

ファイルを全て作成したらコンテナを起動します。
(docker-compose.yamlのあるディレクトリで実行する)

docker-compose build
docker-compose up -d

コンテナが立ち上がってから以下のURLを表示するとNginx上でVueアプリケーションが公開されていることが確認できます。
http://localhost:8080/

15
16
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
15
16