docker

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > 云和虚拟化 > docker > Next.js Docker镜像私有部署

Next.js Docker镜像私有部署从零实现

作者:寒露

这篇文章主要为大家介绍了Next.js Docker镜像私有部署从零实现,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

预备

经过一周的零碎开发,大致完成了雏形。简单完成了文件移动、文件删除、图片预览、视频播放。考虑部署一版看看效果。

package.json 新增下面 scripts

"scripts": {
    "explorer-dev": "npm run -w explorer dev",
    "explorer-build": "npm run -w explorer build",
    "explorer-start": "npm run -w explorer start",
    "explorer-check-types": "npm run -w explorer check-types",
    "explorer-build-docker": "docker build -f explorer.full.Dockerfile -t 192.168.31.17:5000/tool-manager/explorer .",
    "explorer-push-docker": "docker push 192.168.31.17:5000/tool-manager/explorer"
  }

/explorer 新增依赖

pnpm i sharp

用于加速 Image 缩略图的生成

私有镜像仓库

使用官方提供的 registry 镜像

docker run -d -p 5000:5000 --restart always --name registry registry:2

需要注意,这里没有配置镜像卷目录,重建容器时之前上传的镜像与配置会丢失。

主要是下面两个

配置 registry

由于 docker push/pull 需要使用 https。非 https 将会提示失败。可通过配置 insecure-registries 绕过 https 检测。

参考链接-Insecure registries

docker desktop

进入设置页,Docker Engine 菜单,添加

{
...
  "insecure-registries": [
    "192.168.31.17:5000"
  ]
}

docker

vim /etc/docker/daemon.json
{
  "insecure-registries" : ["192.168.31.17:5000"]
}

或者在启动 docker 服务的时候加上参数

--insecure-registry 192.168.31.17:5000

构建 Docker

Dockerfile

使用的官方构建的例子 参考链接 进行特定修改,新增了

流程

FROM node:20.9.0-alpine AS base
# 添加源
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
# Install dependencies only when needed
FROM base AS deps
WORKDIR /app
# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* pnpm-workspace.yaml* ./
COPY explorer/package.json ./explorer/package.json
COPY explorer-manager/package.json ./explorer-manager/package.json
RUN npm config set registry https://registry.npmmirror.com/
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/explorer/node_modules ./explorer/node_modules
COPY --from=deps /app/explorer-manager/node_modules ./explorer-manager/node_modules
COPY . .
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1
RUN npm run explorer-build
# If using npm comment out above and use below instead
# RUN npm run build
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1
# Set the correct permission for prerender cache
RUN mkdir .next
# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=1000:100 /app/explorer/.next/standalone ./
COPY --from=builder --chown=1000:100 /app/explorer/.next/static ./explorer/.next/static
ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"
CMD ["node", "./explorer/server.js"]

分步构建将最大层度的使用 docker 构建缓存。加速构建镜像的过程。还能缩小最终生成镜像大小。

Dockerfile.dockerignore

排除过滤文件。docker 执行 build 时,会自动检索与当前 dockerfile 同名的 *.dockerignore 文件作为排除过滤文件。

用于加速 docker build “transferring dockerfile” 过程。如果不设置,会将 build 指定的上下文加入转移过程中。如果 node\_modules、.next 文件过多,会增加 60s+的时间。

.idea
.git
**.Dockerfile
**.dockerignore
**/node_modules
**/npm-debug.log
**/.next
**/README.md
**/.env.*

项目内使用了 monorepo。所以使用 **. 、**/批量过滤

docker-compose.yml

启动容器模板。172.17.0.1 为本机 docker 服务的 ip 地址。

这里同时配置了 tool-manager/explorer 镜像与 nginx 镜像。并为 nginx 指定 nginx.conf 配置文件

version: '3'
services:
  explorer-app:
    container_name: explorer-app
    image: 172.17.0.1:5000/tool-manager/explorer:latest
    restart: always
    environment:
      - EXPLORER_PATH=/mnt
      - TZ=Asia/Shanghai
    volumes:
      - /mnt:/mnt
    #      - explorer-app-files:/app/explorer/
    networks:
      - share-explorer
    user: 1000:100
  # Add more containers below (nginx, postgres, etc.)
  nginx:
    container_name: explorer-app-nginx
    image: nginx:latest
    environment:
      - TZ=Asia/Shanghai
    volumes:
      - type: bind
        source: ./nginx.conf
        target: /etc/nginx/nginx.conf
      - /mnt:/mnt
    #      - explorer-app-files:/app/explorer/
    depends_on:
      - explorer-app
    ports:
      - '12200:80'
    networks:
      - share-explorer
networks:
  share-explorer:
#    external: true
#volumes:
#  explorer-app-files:
#    external: false

nginx.conf

events {
    worker_connections   1000;
}
http {
    include    /etc/nginx/mime.types;
    upstream nextjs_upstream {
        server explorer-app:3000;
    }
    server {
        listen 80;
        gzip on;
        gzip_proxied any;
        gzip_comp_level 4;
        gzip_types text/css application/javascript image/svg+xml;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        location /_next/static/ {
            expires 365d;
#             alias /app/explorer/.next/static/;
            proxy_pass http://nextjs_upstream;
        }
        location /static/ {
            expires 365d;
            alias /mnt/;
        }
        location / {
            proxy_pass http://nextjs_upstream;
        }
    }
}

也可以使用 - explorer-app-files:/app/explorer/ 共享卷的形式共享 Next.js 的运行静态文件,交给 nginx 进行完全代理alias /app/explorer/.next/static/

但是会有一个问题,当重新部署服务时,由于 explorer-app-files 卷已经存在,新的内容会不生效,需要手动删除旧的卷,再重新启动容器时新的改动才会生效。

启动构建

开发机器执行

$ npm run explorer-build-docker
> share-explorer@1.0.0 explorer-build-docker
> docker build -f explorer.full.Dockerfile -t 192.168.31.17:5000/tool-manager/explorer .
[+] Building 111.4s (23/23) FINISHED                                                                                                                                                                                                                                     docker:desktop-linux
 => [internal] load build definition from explorer.full.Dockerfile                                                                                                                                                                                                                       0.0s
 => => transferring dockerfile: 2.51kB                                                                                                                                                                                                                                                   0.0s
 => [internal] load .dockerignore                                                                                                                                                                                                                                                        0.0s
 => => transferring context: 2B                                                                                                                                                                                                                                                          0.0s
 => [internal] load metadata for docker.io/library/node:20.9.0-alpine                                                                                                                                                                                                                    2.7s
 => [auth] library/node:pull token for registry-1.docker.io                                                                                                                                                                                                                              0.0s 
 => CACHED [base 1/3] FROM docker.io/library/node:20.9.0-alpine@sha256:cb2301e2c5fe3165ba2616591efe53b4b6223849ac0871c138f56d5f7ae8be4b                                                                                                                                                  0.0s 
 => [internal] load build context                                                                                                                                                                                                                                                        0.0s 
 => => transferring context: 243.23kB                                                                                                                                                                                                                                                    0.0s 
 => [base 2/3] RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories                                                                                                                                                                                          0.2s 
 => [base 3/3] RUN apk add --no-cache libc6-compat                                                                                                                                                                                                                                       1.2s 
 => [builder 1/6] WORKDIR /app                                                                                                                                                                                                                                                           0.0s 
 => [runner 2/4] RUN mkdir .next                                                                                                                                                                                                                                                         0.3s 
 => [deps 2/6] COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* pnpm-workspace.yaml* ./                                                                                                                                                                                   0.0s 
 => [deps 3/6] COPY explorer/package.json ./explorer/package.json                                                                                                                                                                                                                        0.0s 
 => [deps 4/6] COPY explorer-manager/package.json ./explorer-manager/package.json                                                                                                                                                                                                        0.0s 
 => [deps 5/6] RUN npm config set registry https://registry.npmmirror.com/                                                                                                                                                                                                               1.3s 
 => [deps 6/6] RUN   if [ -f yarn.lock ]; then yarn --frozen-lockfile;   elif [ -f package-lock.json ]; then npm ci;   elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile;   else echo "Lockfile not found." && exit 1;   fi                             14.1s
 => [builder 2/6] COPY --from=deps /app/node_modules ./node_modules                                                                                                                                                                                                                      3.5s
 => [builder 3/6] COPY --from=deps /app/explorer/node_modules ./explorer/node_modules                                                                                                                                                                                                    0.0s
 => [builder 4/6] COPY --from=deps /app/explorer-manager/node_modules ./explorer-manager/node_modules                                                                                                                                                                                    0.0s
 => [builder 5/6] COPY . .                                                                                                                                                                                                                                                               0.0s
 => [builder 6/6] RUN npm run explorer-build                                                                                                                                                                                                                                            84.8s
 => [runner 3/4] COPY --from=builder --chown=1000:100 /app/explorer/.next/standalone ./                                                                                                                                                                                                  0.2s 
 => [runner 4/4] COPY --from=builder --chown=1000:100 /app/explorer/.next/static ./explorer/.next/static                                                                                                                                                                                 0.0s 
 => exporting to image                                                                                                                                                                                                                                                                   0.3s 
 => => exporting layers                                                                                                                                                                                                                                                                  0.3s 
 => => writing image sha256:cf1f902944d3fcf3e938c8136b781566500b90d9ff79b122c53ecdad035671ef                                                                                                                                                                                             0.0s 
 => => naming to 192.168.31.17:5000/tool-manager/explorer

Building 111.4s (23/23) FINISHED 差不多两分钟时间完成了镜像的构建。

查看镜像信息

$ docker images
REPOSITORY                                      TAG       IMAGE ID       CREATED         SIZE
192.168.31.17:5000/tool-manager/explorer        latest    cf1f902944d3   2 minutes ago   161MB

大小为:161MB

推送镜像

开发机器执行

$ npm run explorer-push-docker

> share-explorer@1.0.0 explorer-push-docker
> docker push 192.168.31.17:5000/tool-manager/explorer

Using default tag: latest
The push refers to repository [192.168.31.17:5000/tool-manager/explorer]
60f05a6e16d5: Pushed 
eee1f67860e5: Pushed 
ff64dffbca6a: Pushed 
fcc511c2a1f1: Pushed 
e44450d578c0: Pushed 
b20d27ca648d: Pushed 
45956122da26: Layer already exists 
e0df4b6a3449: Layer already exists 
86d11448d6ef: Layer already exists 
cc2447e1835a: Layer already exists 
latest: digest: sha256:3b510f7e600e08d8fe7fb2074053a9272385a6d0833ff9e984563d3b1661425b size: 2409

拉取运行容器

需要部署的机器上执行

docker-compose -f explorer.docker-compose.yml up -d

常用 docker 命令

查看当前 docker 的磁盘占用

$ docker system df
TYPE            TOTAL     ACTIVE    SIZE      RECLAIMABLE
Images          3         0         364.2MB   364.2MB (100%)
Containers      0         0         0B        0B
Local Volumes   1         0         0B        0B
Build Cache     74        0         4.481GB   4.481GB

删除构建镜像缓存

$ docker builder prune

构建并后台启动

$ docker-compose up --build -d

删除使用状态的 volumes

$ docker system prune -a

清除悬空镜像

$ docker image prune

以上就是Next.js Docker镜像私有部署从零实现的详细内容,更多关于Next.js Docker镜像私有部署的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文