hexo在docker里测试和部署

2025-08-10 更新

好久不更新,发现 Theme-next 仓库都已经有好几个了。

参考: https://github.com/next-theme/hexo-theme-next/issues/546

1. 构建想法

1.1 方式选择

  1. 是创建一个新的镜像,然后在容器里 git clone 代码,然后对安装后的环境打一个镜像呢?

  2. 还是只创建一个环境镜像,映射本地的代码?这样镜像只保持基础的环境,代码还在宿主机上,不用频繁更新镜像。

方案二是当今绝对的主流和最佳实践。 它完美地平衡了开发效率、部署灵活性和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

# 【关键】将 node_modules 的可执行文件目录添加到环境变量 PATH 中
ENV PATH /app/node_modules/.bin:$PATH
# 这是利用 Docker 缓存的关键!只要这两个文件不变,下面的 npm install 就不会重新执行。
COPY package*.json ./

# 2. 安装 hexo-cli 和项目所有依赖
# --production=false 确保 devDependencies 也被安装
RUN npm install --production=false hexo-cli && npm install --production=false

# 3. 拷贝你博客的所有其他文件(比如 markdown 文章、主题配置等)
# 这一步放在最后,因为这些文件是你最常修改的
COPY . .

# 暴露 hexo server 的默认端口
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
# 【关键技巧】这是一个匿名卷,用于隔离 node_modules 目录。
# 作用:防止本地映射覆盖掉镜像里已经安装好的 node_modules,
# 同时还能避免在你的本地项目文件夹里出现巨大的 node_modules 目录,保持整洁。
- /app/node_modules
command: sh -c "hexo server"

# 部署
hexo-deployer:
image: my-hexo-liuvv
volumes:
# 1. 挂载源码,确保部署的是最新内容
- .:/app
# 2. 挂载你的 SSH 密钥,以便能推送到 GitHub
- ~/.ssh:/root/.ssh:ro
# 3. (新增) 将你主机的 Git 配置挂载到容器中
- ~/.gitconfig:/root/.gitconfig:ro
# 4. (推荐) 保留 node_modules 的匿名卷
- /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