我正在管道中使用 Jenkins Docker 插件来启动后台 mongodb 容器进行测试,使用:
stage('Start') {
steps {
script {
container = docker.image('mongo:latest').run('-p 27017:27017 --name mongodb -d')
}
}
}
我需要获取容器 IP 地址才能连接到它。我在网上找到了一些例子提到
docker.inspect
和 docker.getIpAddress
方法,但它们只是抛出错误,并且根据 Docker 插件的源代码 我相信它们甚至不存在。
有没有办法从
container
对象获取 IP 地址?
这是我的解决方案(请自行测试):
stage('Start') {
steps {
script {
def container = docker.image('mongo:latest').run('-p 27017:27017 --name mongodb -d')
def ipAddress = null
while (!ipAddress) {
ipAddress = sh(
returnStdout: true,
script : "docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mongodb"
)
if (!ipAddress) {
echo "Container IP address not yet available..."
sh "sleep 2"
}
}
echo "Got IP address = ${ipAddress}."
}
}
}
您可以通过捕获它的主机文件并添加一个工作示例来打印一个 cont 的 ip。
根据您的需要,您可以从打印输出中提取实际的 dns 或 ip。
stage('try') {
agent {
docker {
image 'node:20.11.1-alpine3.19'
args " --net test_network --expose 4444 --expose 7900 --shm-size=\"2g\""
reuseNode true
}//docker
}//agent
steps {
sh 'node --version'
sh 'cat /etc/hosts'
sh 'whoami'
} //steps
}//stage
and here is printout:
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
+ node --version
v20.11.1
[Pipeline] sh
+ cat /etc/hosts
127.0.0.1 localhost
172.19.0.6 63aa2b53e92d
[Pipeline] sh
+ whoami
node