从零开始-文件资源管理器-14-Next.js Docker 镜像私有部署

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

  1. 自建 docker registry 私有仓库储存构建好的镜像
  2. 创建 Dockerfile,开发机器构建好镜像后上传至私有 docker 镜像仓库
  3. NAS 使用 Docker Compose 启动容器。通过私有 docker registry 仓库获取镜像运行

预备

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

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

主要是下面两个

  • /var/lib/registry:存放镜像目录地址
  • /etc/docker/registry/:存放配置文件地址

配置 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

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

  1. 阿里的 alpine 源,加速 apk 的安装
  2. 配置 npm 加速源

流程

  1. 使用 20.9.0-alpine 的 node 镜像作为基础(base)镜像,并安装 libc6-compat 库。让后续使用 base 镜像的都拥有 libc6-compat 库
  2. 在(deps)镜像内,将 package.json 复制到对应目录,并执行依赖初始化安装
  3. 将初始化好的依赖复制值运行打包(builder)镜像内,执行 Next.js 编译
  4. 将 Next.js 编译好的文件复制至运行(runner)镜像内。完成整体的创建镜像流程
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;
        }
    }
}
  1. 流量由主机的 12200 端口进入 nginx 的 80 端口。
  2. 通过反向代理至 networks 指定的 share-explorer:3000 文件资源管理器服务的端口
  3. 设置 /_next/static/ 路径的今天缓存 365 天。
  4. 查看原图、视频资源的 /static/ 路由通过 nginx 反代理,不再进入 Next.js 内

也可以使用 - 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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容