웹 개발/Vue

[Vue] Docker 배포 방법 (nginx 서버)

Eu4ng 2022. 10. 4. 20:30

https://stackoverflow.com/questions/54007569/how-to-config-nginx-for-vue-router-on-docker/54193517#54193517

 

How to config nginx for Vue-router on Docker

I'm setting up a docker image from nginx to serve a Vue app as static files. My vue app uses Vue-Router and it works perfectly on an other server. My nginx config is just like this: https://router...

stackoverflow.com

 

1. Vue 프로젝트 폴더 안에 docker 폴더 생성 (src, public 폴더와 동일한 위치에 생성)

2. docker 폴더 안에 Dockerfile과 nginx.conf 파일 작성

* nginx.conf 파일을 설정하지 않으면 새로고침이나 세부 url을 직접 입력할 경우 404 에러 발생

- Dockerfile

# Step 1: Build Vue Project
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Step 2: Create Nginx Server
FROM nginx:stable-alpine as production-stage
COPY docker/nginx.conf /etc/nginx/nginx.conf

COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

- nginx.conf

# Ref: https://cli.vuejs.org/guide/deployment.html#docker-nginx

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 {
    # good practice not to use port 80 inside a container
    # because container should run as non root and they can't run under port < 1024 
    listen       80;
    server_name  localhost;
    location / {
      root   /usr/share/nginx/html;
      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;
    }
  }
}

3. 도커 이미지 빌드 및 파일로 만들기

- docker build --tag ImageName -f docker/Dockerfile .

- docker save -o FileName.tar ImageName