基于docker的gitlab-ci持续集成

概念

GitLab具有内置的持续集成(CI),持续部署和持续交付支持,可用于自动化构建,测试和部署您的应用程序

image

docker镜像下载

docker hub下载gitlab-ce镜像和gitlab-runner镜像

1
2
docker pull gitlab/gitlab-runner:latest
docker pull gitlab/gitlab-ce:latest

安装gitlab-ce

  • 用命令运行docker容器
1
2
3
4
5
6
7
8
docker run --detach \
--hostname mygitlab.com \
--publish 443:443 --publish 81:80 --publish 22:22 \
--name gitlab.abc.net \
--volume /Users/chenshinan/work/dockerFile/gitlab/config:/etc/gitlab \
--volume /Users/chenshinan/work/dockerFile/gitlab/logs:/var/log/gitlab \
--volume /Users/chenshinan/work/dockerFile/gitlab/data:/var/opt/gitlab \
gitlab/gitlab-ce:latest

image

  • 第一次访问需要设置root账号密码

若忘记密码,可以进入容器中重置密码

1
2
3
4
5
6
7
8
9
10
11
12
docker exec -it gitlab镜像id bash
[root@svr34 bin]# gitlab-rails console production
Loading production environment (Rails 4.2.5.2)
irb(main):001:0> user = User.where(id: 1).first
=> #<User id:1 @root>
irb(main):002:0> user.password="12345678"
=> "12345678"
irb(main):003:0> user.password_confirmation="12345678"
=> "12345678"
irb(main):004:0> user.save!
=> true
irb(main):005:0> quit

安装gitlab-runner

  • 用命令运行docker容器
1
2
3
4
5
6
docker run \
-d --name gitlab-runner \
--link gitlab.abc.net \
-v /Users/chenshinan/work/dockerFile/gitlab/runner/config:/etc/gitlab-runner \
-v /var/run/docker.sock:/var/run/docker.sock \
gitlab/gitlab-runner:latest

使用docker来运行gitlab和gitlab-runner,需要用到link参数链接两个容器,绑定数据卷时,docker.sock即为本机的docker.sock

配置gitlab-runner

如果需要gitlab-runner工作的话,需要让gitlab-runner知道gitlab的地址等相关信息,进入runner容器中注册runner

1
2
3
4
5
6
7
docker exec -it gitlab-runner镜像id bash
gitlab-runner register \
--url "http://gitlab.abc.net/ci" \
--registration-token "nMDw9wj3FJDgmjR1wYy9" \
--description "docker-ci-base" \
--executor "docker" \
--docker-image alpine:latest

注册成功后,就可以在http://localhost:81/admin中看到runner,并将runner应用到某个项目上

image

在项目中应用gitlab-ci

image

1
2
3
test:
script:
- ls

commit之后就会自动开始跑ci

image
image

常见错误

注册gitlab-runner时,出现无法链接异常

image

1
2
3
ERROR: Registering runner... failed
runner=nMDw9wj3
status=couldn't execute POST against https://gitlab.abc.net/api/v4/runners: Post https://gitlab.abc.net/api/v4/runners: dial tcp 172.17.0.2:443: getsockopt: connection refused

解决:将http://localhost:81/改为http://gitlab.abc.net/ci即可注册成功

跑ci时出现报错

image

1
2
3
4
5
fatal: unable to update url base from redirection:
asked for: http://gitlab-ci-token:xxxxxxxxxxxxxxxxxxxx@mygitlab.com/root/myproject.git/info/refs?service=git-upload-pack
redirect: https://www.hugedomains.com/domain_profile.cfm?d=mygitlab&e=com
/bin/bash: line 62: cd: /builds/root/myproject: No such file or directory
ERROR: Job failed: exit code 1

解决:出现这个问题的原因好像是gitlab-runner在拉取代码的时候,没有解析到
mygitlab.com,查看gitlab-runner的host文件,里面有mygitlab的映射。暂时通过将gitlab中的extenar_url修改为gitlab容器在docker中的ip地址

1
2
docker exec -it gitlab vi /etc/gitlab/gitlab.rb
external_url 'http://172.17.0.2'

查看容器的ip:docker inspect 容器id

参考文献