2025-08-10 更新
好久不更新,发现 Theme-next 仓库都已经有好几个了。
参考: https://github.com/next-theme/hexo-theme-next/issues/546
1. 构建想法
1.1 方式选择
是创建一个新的镜像,然后在容器里 git clone 代码,然后对安装后的环境打一个镜像呢?
还是只创建一个环境镜像,映射本地的代码?这样镜像只保持基础的环境,代码还在宿主机上,不用频繁更新镜像。
方案二是当今绝对的主流和最佳实践。 它完美地平衡了开发效率、部署灵活性和Docker的哲学。
1.2 每次 npm i 会不会慢
如果镜像每次启动都执行 npm install hexo-cli 安装和 npm i 安装 node_moudles,会不会速度会特别慢?
一个设计良好的 Dockerfile 会利用构建时缓存 (Build-time Caching) 来避免这个问题。
Docker 在构建时是分层的。当你修改了代码,但没有修改 package.json
文件时,Docker 会发现 RUN npm install
这一层没有变化,于是它会直接使用缓存,这个过程快如闪电,可能只需要几毫秒。
2. 安装项目
2.1 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 25 26
| FROM node:lts-alpine
RUN apk add --no-cache git openssh-client
RUN npm config set registry https://registry.npmmirror.com
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY package*.json ./
RUN npm install --production=false hexo-cli && npm install --production=false
COPY . .
EXPOSE 4000
CMD ["hexo", "server"]
|
1.2 docker-compose
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| services: hexo-liuvv: build: context: . dockerfile: Dockerfile image: my-hexo-liuvv container_name: hexo_blog_liuvv ports: - "4000:4000" volumes: - .:/app - /app/node_modules command: sh -c "hexo server"
hexo-deployer: image: my-hexo-liuvv volumes: - .:/app - ~/.ssh:/root/.ssh:ro - ~/.gitconfig:/root/.gitconfig:ro - /app/node_modules command: > sh -c "hexo clean && hexo g -d"
|
2.3 测试和部署
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| docker-compose run --rm hexo-deployer sh -c 'npx npm-check-updates -u'
docker-compose build --no-cache
docker-compose run --rm hexo-deployer sh -c 'npm ls --depth 0'
docker-compose run --rm hexo-deployer sh -c 'ls -al /app'
docker-compose run --service-ports --rm hexo-liuvv
docker-compose run --rm hexo-deployer
|