Nuxt/Vue Production環境容器化
Nuxt
Nuxt Service HOST設定調整為0.0.0.0
nuxt host預設為localhost
也就是說只有本機連的到
在容器環境中外部會無法連線至nuxt服務
因此需要將host改為0.0.0.0讓外部能夠存取
這時候可調整nuxt.config.js的server.host屬性改為0.0.0.0
或是在Dockerfile中設定NUXT_HOST ENV為0.0.0.0
.dockerignore
排除以下檔案/目錄
避免在開發環境中進行COPY時間過慢
Dockerfile
node_modules
.nuxt
Dockerfile(static mode)
若nuxt服務為static mode
使用yarn generate指令進行打包
FROM node:14
WORKDIR /site
ENV NUXT_HOST=0.0.0.0
COPY . /site
RUN yarn install \
&& yarn cache clean \
&& yarn generate
# port依照需求自行修改
CMD ["yarn", "start", "--port=8888"]
Dockerfile(server mode)
若nuxt服務為server mode
使用yarn build指令進行打包
FROM node:14
WORKDIR /site
ENV NUXT_HOST=0.0.0.0
COPY . /site
RUN yarn install \
&& yarn cache clean \
&& yarn build
# port依照需求自行修改
CMD ["yarn", "start", "--port=8888"]
docker-compose.yml(本機測試用)
透過此docker-compose.yml可使用docker-compose啟動服務在本機做測試
version: "3.8"
services:
nuxt-site:
container_name: nuxt-site
build:
context: .
restart: unless-stopped
tty: true
working_dir: /site
ports:
- "8888:8888"
Vue
vue的容器化官方其實給了很完整的範例(ref)
但沒有針對history mode nginx設定特別做說明
因此下面這邊會說明在nginx內的history mode設定
實際production內容在容器內的位置
依照nginx docker image的官方文件
預設的靜態內容直接放在/usr/share/nginx/html目錄中即可
.dockerignore
排除以下檔案/目錄
避免在開發環境中進行COPY時間過慢
Dockerfile
node_modules
在vue public目錄下新增一個nginx.conf檔案
將此nginx.conf放在vue專案的public目錄下
打包完成後才會直接被放在production目錄中
location / {
try_files $uri $uri/ @router;
index index.html;
}
location @router {
rewrite ^.*$ /index.html last;
}
default.conf
這個default.conf將在Dockerfile中被複製到container內的/etc/nginx/conf.d/default.conf
server {
listen 80 default_server;
listen [::]:80 default_server;
root /usr/share/nginx/html;
index index.html index.htm index.nginx-debian.html;
server_name _;
location ~ .(html)$ {
add_header Cache-Control "max-age=0, no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header X-Frame-Options "SAMEORIGIN";
}
location ~ (css|js|map|jpg|jpeg|png|ico|gif|woff|woff2|svg|ttf|eto|br|gz)$ {
add_header Cache-Control "max-age=86400, must-revalidate";
}
# include vue public目錄中的nginx.conf
include /usr/share/nginx/html/nginx.conf;
location ~ /\.ht {
deny all;
}
}
Dockerfile
# build stage
FROM node:lts-alpine as build-stage
COPY . /workspace
RUN cd /workspace \
&& yarn install \
&& yarn build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /workspace/dist /usr/share/nginx/html
COPY docker/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
關於nginx image的類型選擇
除了用上述的stable-alpine版本(Alpine Linux)之外
亦可使用OS為Debian的stable版本
因為apline是非常清量化的OS
光空的image來說
nginx:stable就要143MB
而nginx:stable-alpine只有23MB
這兩個OS的容量差距非常大
實際佈署可視情況來選擇OS