dockerjenkinsdocker-composeenvironment-variablescicd

How to add ".env" in Jenkins via docker-compose


I have an Application that can be initiated via docker-compose. And that docker-compose file uses a ".env" file to get all the secret variables. Now I want to automate it with CI/CD using Jenkins. My question is how do I add ".env" file in that build without making the env file public?

Here is my docker-compose.yml

version: "3"
services:
  my-app:
    image: j0sal/nextjs-13-login
    ports:
      - "3001:3000"
    env_file:
      - .env

If possible I want to keep the .env file specific for that build. Is that possible?


Solution

  • You can add files to the Jenkins credentials store and access them in the pipelines using withCredentials step. So the pipeline will look something like this:

    node('built-in') {
      withCredentials([file(credentialsId: 'secretFile', variable: 'SECRET_FILE')]) {
        sh '''
          docker compose up -d --env SECRET_FILE
          # do whatever you need to do with the containers
        '''
      }
    }
    

    And then the docker-compose.yml file will reference the variable instead of a hardcoded path:

    version: "3"
    services:
      my-app:
        image: j0sal/nextjs-13-login
        ports:
          - "3001:3000"
        env_file:
          - "${SECRET_FILE}"
    

    Ideally you should be using secrets instead of env_file, but that's a different topic.