准备环境
虚拟机两台
centos 7.2 192.168.255.128
centos 7.2 192.168.255.129
maven 3.0.5
java 1.8.0_181
git version 1.8.3.1
Python 2.7.5
docker registry2
项目地址:https://gitee.com/shenduedu/JXC.git 要在自行配好数据库环境
centos 192.168.255.128 装上 maven,java,git
centos 192.168.255.129 装上 java
此处不在累赘
注意:
1 因为要远程执行,所以要在两台虚拟机上配置ssh key
ssh-keygen -t rsa
一路按回车,然后将生成的公钥复制到 129机器上
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
2 要在码云好配置好公钥
因为要用git 拉代码
部署流程大概是
1 git 将代码 下载到指定目录
2 maven 将代码打包
3 将maven打包后的war包复制 到 dockerfile所在目录
4 docker build 指定版本的镜像文件
5 push 到 私有仓库
6 将准备好的docker-compose.yml文件 scp到运行服务的机器
7 远程执行 docker-compose up .
本次 运行 的 sql,dockfiler , docker-compose.yml都在 :https://gitee.com/shenduedu/JXC.git 项目中
注意,在向 docker 私有仓库 pull 镜像时 可能会遇到
Get https://192.168.255.128:5000/v1/_ping: http: server gave HTTP response to HTTPS client 错误
解决办法是
echo '{ "insecure-registries":["192.168.255.128:5000"] }' > /etc/docker/daemon.json
然后重启docker
systemctl restart docker
为可方便演示,我代码都是采用硬编码的方式,请读者们谅解
部署 docker registry2
搭建私有仓库
docker run -d -p 5000:5000 --restart=always --name registry2 registry:2
curl -X GET http://localhost:5000/v2/_catalog 查看私有仓库 所用镜像
列出指定镜像的所有标签
curl -X GET http://localhost:5000/v2/jxc/tags/list
dockerfile 代码
FROM java:8
VOLUME /tmp
ADD JXC-0.0.1-SNAPSHOT.war /app.war
EXPOSE 80
ENTRYPOINT ["java","-jar","/app.war"]
docker-compose.yml
version: '2'
services:
jxc:
image: 192.168.255.128:5000/jxc:0.0.3
ports:
- "8080:80"
python代码
# -*- coding: UTF-8 -*-
import os
import sys
if os.path.exists('/usr/local/deployer.lock'):
print '程序正在执行.................'
sys.exit(1)
file = open('/usr/local/' + 'deployer' + '.lock','w')
file.close()
res = os.system('rm -rf /usr/local/gitsource/*')
if res != 0:
print 'delete gitsource files fail'
res =os.remove('/usr/local/deployer.lock')
sys.exit(1)
res = os.system('cd /usr/local/gitsource/ && git clone https://gitee.com/shenduedu/JXC.git')
if res != 0:
print 'https://gitee.com/shenduedu/JXC.git fail'
res =os.remove('/usr/local/deployer.lock')
sys.exit(1)
res = os.system('cd /usr/local/gitsource/JXC/ && mvn clean package')
if res != 0:
print 'mvn package fail'
res =os.remove('/usr/local/deployer.lock')
sys.exit(1)
# 复制项目到 dockerfile 当前目录
res = os.system('/bin/cp /usr/local/gitsource/JXC/target/JXC-0.0.1-SNAPSHOT.war /usr/local/dockerfile/')
# docker build 生成镜像
res = os.system('cd /usr/local/dockerfile/ && docker build -t jxc:0.0.3 .')
# 给生成的 镜像 打 tag
res = os.system('docker tag jxc:0.0.3 localhost:5000/jxc:0.0.3')
# 把生成的镜像 push 到 私有仓库
res = os.system('docker push localhost:5000/jxc:0.0.3')
# 将当前目录的 docker-compose.yml 复制到远程机器
res = os.system('cd /usr/local/dockerfile/ && scp docker-compose.yml 192.168.255.129:/opt/jxc/')
# 从私有仓库中拉取镜像
res = os.system('ssh [email protected] "docker pull 192.168.255.128:5000/jxc:0.0.3"')
# 执行 docker-compose.yml
res = os.system('ssh [email protected] "cd /opt/jxc && docker-compose up"')
res =os.remove('/usr/local/deployer.lock')
欢迎加入 微服务交流群 222700500