Reputation: 2403
I'm trying to use docker-compose
with environment variable for the image name set by the Jenkinsfile
but it is not working.
I have a Jenkinsfile
containing
node() {
stage('Checkout') {
cleanWs()
git credentialsId: 'xxx', url: 'ssh://git@...'
}
stage('Build') {
withMaven(maven: 'maven-3.5.3') {
sh 'mvn clean package'
def pom = readMavenPom file:'pom.xml'
JAR_FILE = pom.artifactId + "-" + pom.version + ".jar"
JAR_VERSION = pom.version
}
}
stage('Build Docker Image') {
echo "Docker Build ..."
docker.withTool('docker') {
app = docker.build("microservices/my-service:${JAR_VERSION}","--build-arg JAR_FILE=${JAR_FILE} .")
}
}
stage('Running Docker Container') {
echo "Docker Run ..."
withEnv(['VERSION=1.0.0']) {
docker.withTool('docker') {
sh "docker-compose rm -f -s -v"
sh "docker-compose up -d"
}
}
cleanWs()
}
}
And a docker-compose.yml
like
version: '3.6'
services:
my-service:
image: microservices/my-service:${VERSION}
container_name: my-service
...
Everything is working fine excepts that the last stage is not using my environment variable.
Docker Run ...
[Pipeline] withEnv
[Pipeline] {
[Pipeline] tool
[Pipeline] withEnv
[Pipeline] {
[Pipeline] sh
[my-service] Running shell script
+ docker-compose rm -f -s -v
The VERSION variable is not set. Defaulting to a blank string.
Upvotes: 5
Views: 15002
Reputation: 2403
After adding a sh "printenv"
juste before the sh "docker-compose ..."
I saw
Version=1.0.0
I don't know why withEnv(['VERSION=1.0.0'])
give me Version=1.0.0
but using, in the docker-compose-yml
image: microservices/my-service:${Version}
in place of image: microservices/my-service:${VERSION}
works fine.
Upvotes: 4
Reputation: 1347
Did you try to put the following environment
in your Jenkinsfile?
{
...
stage('Running Docker Container') {
echo "Docker Run ..."
docker.withTool('docker') {
sh "docker-compose rm -f -s -v"
sh "docker-compose up -d"
}
cleanWs()
}
environment {
VERSION = "1.0.0"
}
}
Additionnaly, you can use default values using a .env
file but @mulg0r (permalink) is explaining this solution in his answer. You can read the variable substitution in docker-compose documentation for further information.
Upvotes: 0
Reputation: 3691
You need to save these ENV in a file (output of jenkinsfile, input of dockercompose file). Then, you have two possibilities:
If you need your ENV inside my-service
container save your ENV in ./your_envfile.env
, and just add
version: '3.6' services: my-service: image: microservices/my-service:${VERSION} container_name: my-service env_file: ./your_envfile.env
If you need to use your ENV in docker-compose file, as I see in your image
section with ${VERSION}
, you need to save your ENV in .env
file.
.env
file must be in the same path that you execute docker-compose, or at least a symlink named ./env
which points somewhere you've saved ENV in this format:
VERSION=1.0.0
...
Upvotes: 3