Java---DockerApi

环境

ubuntu

开始

想要在java中还是在其他方式访问dockerAPI都需要设置一个端口,运行以下命令:进入docker.service

1
vi /lib/systemd/system/docker.service

找到Execstart=/usr/bin/dockerd后加上 -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock 退出并且保存,运行以下命令:

1
2
systemctl daemon-reload
service docker restart//重启启动docker

运行:netstat -nlp |grep 2375可以查看2375是否已经被监听
在这里插入图片描述
这时可以通过java来访问docker了,或者可以在浏览器的地址栏中访问docker了,在浏览器地址栏中访问:http://ip:2375/info 返回的数据是以json的格式展示 ,IP地址为centos机器的IP地址,如果是云服务器则是公网IP地址。格式如下:

1
ID: "XLNC:EK3V:NIND:4P2R:PWXT:RRCX:YG3G:LJAH:QT3D:6J2O:6RVG:T2RL",Containers:6,ContainersRunning: 0,ContainersPaused: 0,ContainersStopped: 6,Images: 36,Driver:"overlay2",DriverStatus:[["Backing Filesystem","extfs"],["Supports d_type","true"],["Native Overlay Diff","true"]],SystemStatus: null,Plugins: {Volume: ["local"],Network: ["bridge","host","ipvlan","macvlan","null","overlay"],Authorization: null,Log: ["awslogs","fluentd","gcplogs","gelf","journald","json-file","local","logentries","splunk","syslog"]},

还有其它的操作比如—列出容器:(更多的操作参考https://docs.docker.com/engine/api/v1.24/

1
http://ip:2375//v1.24/containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1
安全链接

上面简单的进行docker的连接,但是会有暴露端口的漏洞存在,也就是说黑客获取了你的ip地址以及端口号以后可以对你的docker进行破坏(为所欲为),这种方式在实际项目中不可取,必须做安全连接,通过密钥的方式做认证。
如何在服务器上或者本地虚拟机上生成密钥文件可参考官方文档:https://docs.docker.com/engine/security/https/#create-a-ca-server-and-client-keys-with-openssl

1.首先选择一个存放密钥文件的地方 我这里选择/home/user/certs来存放 /user/certs是我自己创建的 进到certs文件中运行

1
2
3
4
5
6
7
8
9
openssl genrsa -aes256 -out ca-key.pem 4096 
[root@ywh certs]# openssl genrsa -aes256 -out ca-key.pem 4096
Generating RSA private key, 4096 bit long modulus
.........................++
..............................................................................................................................................++
e is 65537 (0x10001)
Enter pass phrase for ca-key.pem: //这里会让设置密码我设置的是123456 这个以后会用到
Verifying - Enter pass phrase for ca-key.pem: //这里是让你再次输入密码确认密码不会显示出来,你只管输入按回车就可以了
[root@ywh certs]#

2.运行:openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem 最后还有个邮箱的我没有放上来 填什么都行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

[root@ywh certs]# openssl genrsa -aes256 -out ca-key.pem 4096
Generating RSA private key, 4096 bit long modulus
.........................++
..............................................................................................................................................++
e is 65537 (0x10001)
Enter pass phrase for ca-key.pem: //输入你刚才的密码
Verifying - Enter pass phrase for ca-key.pem:
[root@ywh certs]# openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem
Enter pass phrase for ca-key.pem:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:cn //从这开始让你输入一些信息以便进行加密,其实填什么也无所谓
State or Province Name (full name) []:ywh
Locality Name (eg, city) [Default City]:bj
Organization Name (eg, company) [Default Company Ltd]:xx
Organizational Unit Name (eg, section) []:xx
Common Name (eg, your name or your server's hostname) []:192.168.80.93 //值得注意的是这里要填写你的ip地址

3.运行:openssl genrsa -out server-key.pem 4096 生成server-key.pem

1
2
3
4
5
6

[root@ywh certs]# openssl genrsa -out server-key.pem 4096
Generating RSA private key, 4096 bit long modulus
................................................................++
.........................++
e is 65537 (0x10001)

4.运行:openssl req -subj "/CN=192.168.80.93" -sha256 -new -key server-key.pem -out server.csr CN中写你在上面填写的IP

1
openssl req -subj "/CN=192.168.80.93" -sha256 -new -key server-key.pem -out server.csr

5.运行:echo subjectAltName = DNS:192.168.80.93,IP:192.168.80.93,IP:0.0.0.0,IP:127.0.0.1 >> extfile.cnf 配置哪些主机可以访问你 0.0.0.0代表所有主机都可以通过密钥文件的方式访问

6.运行 echo extendedKeyUsage = serverAuth >> extfile.cnf

7.运行:openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf

1
2
3
4
5
6
[root@ywh certs]# openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \
> -CAcreateserial -out server-cert.pem -extfile extfile.cnf
Signature ok
subject=/CN=192.168.0.3
Getting CA Private Key
Enter pass phrase for ca-key.pem:

8.运行:openssl genrsa -out key.pem 4096

9.运行:openssl req -subj '/CN=client' -new -key key.pem -out client.csr

10.运行:echo extendedKeyUsage = clientAuth >> extfile.cnf

11.运行:openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile.cnf

1
2
3
4
5
6
[root@ywh certs]# openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \
> -CAcreateserial -out cert.pem -extfile extfile.cnf
Signature ok
subject=/CN=client
Getting CA Private Key
Enter pass phrase for ca-key.pem:

12.rm -v client.csr server.csr 删除临时文件,配置权限chmod -v 0400 ca-key.pem key.pem server-key.pem chmod -v 0444 ca.pem server-cert.pem cert.pem
现在在/home/user/certs下应该有8个文件

1
2
3
4
5
6
7
8
9
10
[root@ywh certs]# ll
总用量 40
-r--------. 1 root root 3326 8月 30 10:44 ca-key.pem
-r--r--r--. 1 root root 2065 8月 30 10:48 ca.pem
-rw-r--r--. 1 root root 17 8月 30 11:04 ca.srl
-r--r--r--. 1 root root 1895 8月 30 11:04 cert.pem
-rw-r--r--. 1 root root 117 8月 30 11:04 extfile.cnf
-r--------. 1 root root 3243 8月 30 11:03 key.pem
-r--r--r--. 1 root root 1899 8月 30 11:02 server-cert.pem
-r--------. 1 root root 3247 8月 30 10:53 server-key.pem

13.找docker.service文件 vi /lib/systemd/system/docker.service 改成如下

1
ExecStart=/usr/bin/dockerd -D --tlsverify=true --tlscert=/home/user/certs/server-cert.pem --tlskey=/home/user/certs/server-key.pem --tlscacert=/home/user/certs/ca.pem -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock

14.运行

1
2
3
systemctl daemon-reload 
service docker restart //重启docker
systemctl status docker //这条命令可以看见你是否设置的生效

配置好安全连接以后在地址栏中是不可以访问的了,如果还可以访问是不对的 因为你没有使用密钥文件的方式访问
这时候需要通过密钥来认证以后才能访问了,可以把密钥文件下载到本机的磁盘上.
需要下载到本地的文件有:1.ca-key.pem 2.ca.pem 3.cert.pem 4.key.pem
Docekr-java官方推荐的连接方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//进行安全认证
DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerTlsVerify(true)
.withDockerCertPath("F:/data/local/").withDockerHost("tcp://192.168.0.3:2375")
.withDockerConfig("F:/data/local/").withApiVersion("1.38").withRegistryUrl("https://index.docker.io/v1/")
.withRegistryUsername("dockeruser").withRegistryPassword("ilovedocker")
.withRegistryEmail("dockeruser@github.com").build();
DockerCmdExecFactory dockerCmdExecFactory = new JerseyDockerCmdExecFactory()
.withReadTimeout(1000)
.withConnectTimeout(1000)
.withMaxTotalConnections(100)
.withMaxPerRouteConnections(10);
//进行连接
DockerClient dockerClient = DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(dockerCmdExecFactory).build();
Info info = dockerClient.infoCmd().exec();
System.out.println(info);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dockerHost:地址是你docker所在的宿主机的外网地址以及你开放的端口号

dockercertPath:放入的是你密钥在windows的文件存放地址

dockerconfig:放的是什么我不太清楚,但是我放入密钥文件地址也没出错

apiVersion:dockerAPI的版本,可通过docker version命令在宿主机上获取版本号

RegistryUrl:这个按着默认的写即可

.withRegistryUsername("dockeruser"):默认

.withRegistryPassword("ilovedocker"):默认

.withRegistryEmail("dockeruser@github.com"):默认

结果

以上就可以在java中连接docker-api了,可以进行安全的连接了,没有密钥文件是不可能访问到的。如果直接通过ip访问出现如下:Client sent an HTTP request to an HTTPS server.

 wechat
欢迎您扫一扫上面的微信公众号,订阅我的个人公众号!
坚持技术分享!