最近在做『互联网 +』项目,作为组里唯一计算机专业的我需要制作一个网页展示产品,奈何我没有学习过前端知识,整不出来。灵机一动决定新建一个hexo
博客,利用现成的框架直接搭网页,并利用自己的域名展示出来。为了不和自己的博客冲突,同时方便以后博客搬迁,决定用容器隔离搭建。正好学了下 docker,在此利用并记录一下。
运行环境
本地计算机:Windows 10
服务器:阿里云服务器 CentOS 8.2
容器:docker 20.10.2
博客框架:Hexo
大致思路
- 建立两种容器,一种用于部署静态页面,一种用于
nginx
的代理转发 - 在本地计算机搭建 Hexo 环境并渲染
- 容器一搭建
ssh
和nginx
环境 - 容器二搭建
nginx
环境 - Hexo 通过 hexo d 命令通过公钥登录容器 git 用户
- 将静态页面推送至的 git 仓库
- 容器将页面拉取至网站的根目录下,通过
nginx
部署 - 容器二监听端口并做代理转发
环境搭建
本地计算机环境搭建
安装 Node.js
进入官网下载:https://nodejs.org/zh-cn/
打开 cmd 验证 node.js 和 npm
1 | node -v |
npm 安装淘宝源
1 | npm install -g cnpm --registry=http://registry.npm.taobao.org |
验证 cnpm
1 | cnpm -v |
安装 Hexo
在磁盘中新建 blog 文件夹存放个人博客,并 cmd
1 | cnpm install -g hexo-cli |
验证 hexo
1 | hexo -v |
初始化 blog 文件夹
1 | hexo init |
启动 hexo 服务
1 | hexo server |
如果初始化失败,则进行
1 | npm install hexo-server --save |
通过 http://localhost:4000/ 访问个人博客
安装 Git
进入官网下载:https://git-scm.com/downloads
打开 git bash 进行初始化
1 | git config --global user.name "username" |
检验 git 设置
1 | git config --global --list |
服务器环境搭建
打开服务器端口
打开安全组,添加安全组规则
设置二级域名
为域名做解析
启动配置容器一
Dockerfile 我不太会写,决定拉一个容器从头搞。
拉取ubuntu
镜像并启动
1 | docker pull ubuntu |
服务器的 1022 端口映射到容器的 22 端口用于ssh
;1080 端口映射到容器的 80 端口,用于部署
设置北京外国语大学的源
1 | cat > /etc/apt/sources.list<<EOF |
更新并下载软件
1 | apt-get update |
修改 /etc/ssh/sshd_config 中 22 端口前的注释
启动 ssh
1 | /etc/init.d/ssh restart |
创建部署目录
1 | mkdir -p /home/www/hexo |
更改 nginx 的配置文件
1 | vim /etc/nginx/nginx.conf |
1 | server { |
启动 nginx
1 | nginx -c /etc/nginx/nginx.conf |
创建 git 用户
1 | useradd -m git |
修改权限
1 | chmod 740 /etc/sudoers |
为 git 用户添加权限
1 | # Next comes the main part: which users can run what software on |
修改回原来的权限
1 | chmod 400 /etc/sudoers |
设置 git 用户密码
1 | sudo passwd git |
git 用户的 ssh 免密公钥登录
回到本地计算机,在桌面打开 git bash
1 | ssh-keygen -t rsa |
进入本地计算机的用户根目录(C:\Users\ASUS)的.ssh 目录,复制 id_rsa.pub 中的内容
回到容器
1 | su git |
将 id_rsa.pub 中的内容复制进.ssh/authorized_keys
设置权限
1 | chmod 600 ~/.ssh/authorized_keys |
在本地计算机上使用 ssh 链接服务器
1 | ssh -v git@xxx.xxx.xxx.xxx(阿里云公网IP) |
配置 Git 仓库
在 git 用户下创建仓库
1 | su git |
向文件中写入
1 |
|
赋予文件权限
1 | chmod +x ~/hexo.git/hooks/post-receive |
根据个人多次的错误,在这里重启 nginx
1 | nginx -s reload -c /etc/nginx/nginx.conf |
制作镜像
提交容器并制作成镜像
1 | docker stop blog |
然后重新启动两个容器分别部署不同的博客,对应的端口需要区分开
1 | docker run -it -h blog-xQmQ --name blog-xQmQ -p 1080:80 -p 1022:22 blog bash -c "/etc/rc.d/rc.local;/bin/bash" |
然后启动ssh
和nginx
启动配置容器二
这个容器只需要简单的配置一下nginx
即可
我没有使用nginx
的镜像,选择自己重新做一个
1 | docker run -it -h nginx --name nginx -p 80:80 centos bash |
这里的端口必须用服务器的 80 端口做映射,域名访问时默认用 80 端口
下载nginx
并修改配置文件
1 | vim /etc/nginx/nginx.conf |
1 | server { |
监听 1080 端口的转发到 xStack (xqmq.icu),这是我自己的博客;监听 2080 端口的转发到 cvi.xqmq.icu,这是项目网站
然后重启容器二
本地计算机 hexo 配置
进入本地计算机的 blog 文件夹下,针对不同的 blog 打开_config.yml 文件进行相应的修改
1 | deploy: |
下载插件,打开 git bash
1 | npm install hexo-deployer-git --save |
使用 Hexo 生成、发布个人博客
1 | hexo clean && hexo g && hexo d |
然后就可以用不同的二级域名访问不同的博客了