使用 Docker 容器化 Vue 專案

做法

新增 docker-compose.yaml 檔:

1
2
3
4
5
6
7
8
9
version: "3"

services:
app:
container_name: vue-docker-example
build: .
ports:
- "8080:80"
restart: always

新增 Dockerfile 檔:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# build stage
FROM node:lts-alpine as build-stage

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

RUN npm run build

# production stage
FROM nginx:stable-alpine as production-stage

COPY --from=build-stage /app/dist /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

編譯並啟動容器:

1
docker-compose up -d --build

瀏覽網頁

前往 http://127.0.0.1:8080 瀏覽。

程式碼

參考資料