介绍
之前用docker的时候想到gitlab可以直接提交代码触发docker编译部署,非常方便,于是试验了一个单体vue项目如何使用gitlab和docker的强大功能进行编译发布,此教程仅供参考,适用于公司或者个人测试。
一、安装gitlab-runner,在runner机器上安装git等
由于公司gitlab版本是8.x,比较老,只能安装1.x版本的gialab-runner,这里比较注意的是,一般runner和gitlab会分别安装到两台服务器上,具体安装步骤可以参考这篇文章。安装好之后创建两个runner:一个docker类型runner,打上CI标签;一个shell类型runner,打上CD标签。因为会使用到shell的runner,所以需要安装git,安装过程不再赘述,当然如果你runner不是这样用,可能还需要安装nodejs等环境。
二、编写Dockerfile
在项目根目录下新建docker目录,编写Dockerfile,注意相对路径问题:
# 设置基础镜像
FROM nginx
#设置CTS时区
RUN cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' >/etc/timezone
# 将dist文件中的内容复制到 /usr/share/nginx/html/ 这个目录下面
COPY ./dist /usr/share/nginx/html/
#用本地的 default.conf 配置来替换nginx镜像里的默认配置
COPY docker/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx","-g","daemon off;"]
同样在docker目录下新增Nginx配置文件default.conf:
server {
listen 80;
server_name localhost;
#charset koi8-r;
access_log /var/log/nginx/host.access.log main;
error_log /var/log/nginx/error.log error;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
三、在gitlab上添加已有runner,创建.gitlab-ci.yml文件
以上工作准备就绪之后在gitlab上添加两个runner,分别对应第一步CI和CD标签的runner,顾名思义,CI用于编译打包,CD用于部署运行。没有.gitlab-ci.yml文件的在项目根目录新建该文件,内容如下:
job-build:
image: node:alpine
stage: build
only:
- master
tags:
# ci是docker类型的runner
- ci
script:
- npm install -g cnpm --registry=https://registry.npm.taobao.org
- cnpm install --progress=false
- cnpm run build
artifacts:
expire_in: 1 week
paths:
- dist
- docker
job-release:
stage: deploy
only:
- master
dependencies:
- job-build
tags:
# cd是shell类型的runner
- cd
script:
- docker build -f docker/Dockerfile -t ngnix/app:v1.0.0 .
- if [ $(docker ps -aq --filter name=app-test) ]; then docker rm -f rhea-cms;fi
- docker run -p 80:80 --name app-test -d ngnix/app:v1.0.0
这里使用到了gitlab的artifacts功能,感兴趣的可以去看官方文档,类似缓存的作用,第二步发布的时候就无需拉取代码编译直接使用上一步归档的dist和docker文件夹。提交所有更改之后所有master分支的提交就会触发一系列编译部署操作了。
遇到的问题:
1.gitlab-runner执行docker命令的时候遇到一个问题,因为使用的是gitlab-runner用户权限不够,结果按照网上教程和更改用户分组都没用。
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
后来找到一个解决方案:
usermod -aG docker gitlab-runner
sudo service docker restart
完美解决。
2.使用gitlab-ci runner拉取git代码遇到这个问题,重新编译安装git都没用
fatal: unable to find remote helper for 'http'
后来发现是编译安装git的时候缺少了curl-devel的lib依赖,yum安装依赖再重新编译安装git就可以了。
$ yum install curl-devel
$ # cd to wherever the source for git is
$ cd /usr/local/src/git-1.7.9
$ ./configure
$ make
$ make install