查看并拉取docker镜像
# 查看镜像
docker search jenkins
# 拉取镜像
docker pull jenkins/jenkins:2.319.1-lts
docker-compose.yml文件
mkdir -p /usr/local/docker/jenkins_docker
cd /usr/local/docker/jenkins_docker
vim docker-compose.yml
version: '3.1'
services:
jenkins:
image: 'jenkins/jenkins:2.319.1-lts'
container_name: jenkins
restart: always
ports:
- '8080:8080'
- '50000:50000'
volumes:
- './data:/var/jenkins_home'
运行命令
# 启动jenkins容器
docker-compose up -d
# 如果出现权限问题,则执行以下命令后重新启动jenkins容器
chmod -R 777 data
# 查看初始密码
docker logs jenkins
jenkins内部使用docker
# 修改docker.sock文件的拥有者及权限
cd /var/run
chown root:root docker.sock
chmod o+rw docker.sock
# 添加数据卷
cd /usr/local/docker/jenkins_docker
vim docker-compose.yml
- '/var/run/docker.sock:/var/run/docker.sock'
- '/usr/bin/docker:/usr/bin/docker'
- '/etc/docker/daemon.json:/etc/docker/daemon.json'
# 验证jenkins容器内部是否可以使用docker命令
docker exec -it jenkins bash
docker version
jenkins流水线
创建流水线项目
流水线配置(示例)
pipeline {
agent any
stages {
stage('拉取git仓库代码') {
steps {
checkout scmGit(branches: [[name: '${tag}']], extensions: [], userRemoteConfigs: [[credentialsId: 'gitee', url: 'https://gitee.com/xhtang/fso.git']])
}
}
stage('制作自定义Docker镜像') {
steps {
dir('src') {
sh 'docker build -t fso-api:${tag} -f docker/Dockerfile-Api .'
}
}
}
stage('将自定义镜像推送到Docker仓库') {
steps {
sh 'docker tag fso-api:${tag} registry.cn-shenzhen.aliyuncs.com/fso/fso-api:${tag}'
sh 'docker push registry.cn-shenzhen.aliyuncs.com/fso/fso-api:${tag}'
sh 'docker rmi registry.cn-shenzhen.aliyuncs.com/fso/fso-api:${tag}'
sh 'docker rmi fso-api:${tag}'
}
}
stage('拉取并运行Docker镜像') {
steps {
sshPublisher(publishers: [sshPublisherDesc(configName: 'tencent', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''docker ps -a | grep fso-api | awk \'{print $1}\' | xargs docker stop
docker ps -a | grep fso-api | awk \'{print $1}\' | xargs docker rm
docker rmi registry.cn-shenzhen.aliyuncs.com/fso/fso-api:$tag
docker run -p 5001:5001 --restart=always --name fso-api -d registry.cn-shenzhen.aliyuncs.com/fso/fso-api:$tag''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '', remoteDirectorySDF: false, removePrefix: '', sourceFiles: '')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: false)])
}
}
stage('删除<none>的Docker镜像') {
steps {
//运行后jenkins此步骤会失败,但是docker的确已删除<none>的镜像,未找到解决方案,暂不理会
sh 'docker images | grep \\<none\\> | awk "{print $3}" | xargs docker rmi'
}
}
}
}
构建并运行项目
检查docker镜像及容器
安全配置
安装Role-based Authorization Strategy插件
全局安全配置
Authentication 选择不要记住我
安全域 选择Jenkins专有用户数据库
授权策略选择 Role-Based Strategy