使用 Docker 容器化 Nuxt 3.0 專案

SSR 模式

新增 .env 檔:

1
APP_PORT=3000

新增 docker-compose.yaml 檔:

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

services:
app:
container_name: my-nuxt-app
build: .
restart: always
ports:
- "${APP_PORT}:3000"

新增 Dockerfile 檔:

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

WORKDIR /app

COPY . .

RUN npm ci
RUN npm run build

RUN rm -rf node_modules
RUN npm ci --only=production

# final stage
FROM node:16-alpine

WORKDIR /app

COPY --from=builder /app .

ENV HOST 0.0.0.0
EXPOSE 3000

CMD [ "node", ".output/server/index.mjs" ]

新增 .dockerignore 檔。

1
2
3
node_modules
.vscode
.git

編譯並啟動容器:

1
docker-compose up -d --build

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

SSG 模式

新增 .env 檔:

1
APP_PORT=3000

新增 docker-compose.yaml 檔:

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

services:
app:
container_name: my-nuxt-app
build: .
restart: always
ports:
- "${APP_PORT}:80"

新增 Dockerfile 檔:

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

WORKDIR /app

COPY . .

RUN npm ci
RUN npm run generate

# final stage
FROM nginx:alpine

COPY --from=builder /app/.output/public /usr/share/nginx/html

EXPOSE 80

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

新增 .dockerignore 檔。

1
2
3
node_modules
.vscode
.git

編譯並啟動容器:

1
docker-compose up -d --build

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