使用Docker搭建Hugo博客

# 环境

# 系统软件环境

  • Server: Debian 11

  • Docker: 20.10.5

# 环境安装

1
2
3
4
5
6
#更新包
apt-get install update
#安装Docker
apt-get install docker.io -y
#安装Docker-Compose
apt-get install docker-compose

注:需具备Linux系统简单操作能力,需会使用Docker基本命令

# 简述

陆续也使用过一些博客程序,例如Hexo、Vuepress等,发现Hugo的一个主题各方面很符合审美,因此准备将博客迁移。

# 目录示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
.
├── docker-compose.yml
├── Dockerfile
├── LICENSE
├── README.md
└── src
    ├── assets
    ├── config.yaml
    ├── content
    ├── resources
    ├── static
    └── themes

# 实操

# 创建相关的目录

1
2
3
4
5
6
7
8
#博客根目录
mkdir doduo.cc
#博客源代码目录
mkdir src
#头像文件目录
mkdir assets/img
#静态文件目录
mkdir static

# 获取主题示例

博客Github地址:hugo-theme-stack

进入 doduo.cc/src ,执行以下命令

1
2
3
4
5
#克隆主题源代码
git clone https://github.com/CaiJimmy/hugo-theme-stack/ themes/hugo-theme-stack
#复制示例网站源码
cp -r ./themes/hugo-theme-stack/exampleSite/content .
cp ./themes/hugo-theme-stack/exampleSite/config.yaml .

content 此目录保存文章数据,config.yaml 网站自定义配置,可以参考hugo-theme-stack官方教程config.yaml 需要配置 baseurl 才可以正常展示。

# 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
FROM node:14-alpine as node_modules

ENV LANG en_US.UTF-8
ENV LANGUAGE en_US.UTF-8
ENV LC_ALL=en_US.UTF-8

RUN echo "Asia/Shanghai" > /etc/timezone

WORKDIR /app

FROM klakegg/hugo:0.107.0-ext-alpine as hugo

WORKDIR /src

COPY ./src/ /src/

# 生成静态文件
RUN hugo

# nginx web 服务器
FROM nginx:1.19.7-alpine

RUN  rm -rf /usr/share/nginx/html/*
COPY --from=hugo /src/public /usr/share/nginx/html

# docker-compose.yml

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

services:
  server:
    build:
      context: .
    container_name: hugo-server
    restart: always
    ports:
      - "20040:80"

# 部署

部署网站

1
docker-compose up --build -d

删除中间镜像

1
docker rmi $(docker images -f "dangling=true" -q)

# Nginx反向代理配置

 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
server {
    listen 20443 ssl;
    server_name blog.doduo.cc;
    ssl_certificate  /etc/nginx/cert/doduo.cc/fullchain.cer;
    ssl_certificate_key /etc/nginx/cert/doduo.cc/doduo.cc.key;

    location ~ /tags.*[^/]$ {
        try_files $uri @rewrite;
    }
    location ~ /categories.*[^/]$ {
        try_files $uri @rewrite;
    }
    location @rewrite {
        return 302 $scheme://$http_host$uri/;
    }

    location / {
        proxy_pass  http://96.43.94.91:20040;
    }
}

server {
    listen 80;
    server_name blog.doduo.cc;
    rewrite ^(.*)$ https://$host$1 permanent;
}

# 参考