如何使用jenkins从docker项目发送env变量

yruzcnhs  于 2023-08-03  发布在  Jenkins
关注(0)|答案(1)|浏览(123)

我对这一切都是新手。我正在使用Docker容器化Laravel项目。我使用Dockerfile作为镜像,使用Docker-compose作为完整环境。在本地,我通过Dockerfile发送.env文件,它正在工作。
所以,我将代码设置到我的Github帐户并安装了Jenkins。当我尝试使用Jenkins管道运行代码时,它返回我无法访问我的数据库(Mysql),并显示此错误。
SQLSTATE[HY 000] [2002]连接拒绝(SQL:select * from information_schema.tables where table_schema = forge and table_name = migrations and table_type = 'BASE TABLE')
在检查jenkins创建的容器后,.env文件不存在。我如何通过管道发送env变量到工作?
我将发送我的Dockerfile、docker-compose.yml和Jenkinsfile。
Dockerfile

FROM php:8.2-apache

ENV COMPOSER_ALLOW_SUPERUSER 1

# Install dependencies
RUN apt-get update && \
    apt-get install -y \
    libzip-dev \
    zip \
    curl \
    git \
    openssl

# Enable mod_rewrite
RUN a2enmod rewrite

# Install PHP extensions
RUN docker-php-ext-install mysqli pdo pdo_mysql zip gd

ENV APACHE_DOCUMENT_ROOT=/var/www/html/public
RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

## Set the working directory
WORKDIR /var/www/html

## Copy the application code for HTML folder
COPY . /var/www/html

## Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

## Install project dependencies
RUN composer install

##
RUN cp .env.example .env && php artisan key:generate

## Set permissions
RUN chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache

字符串
docker-compose.dev.yml

version: '3.8' #versão do composer
services:
  laravel:
    container_name: eventos-dev # nome do container para o docker
    image: henriquemg/gcs-laravel:latest # imagem usada
    build:
      context: . # inicialização
      dockerfile: Dockerfile # Usa o Dockerfile (da mesma pasta) como base
    ports:
      - 8003:80 # da porta 80(DOCKER(DENTRO)) para a porta 8001(EXTERNO(VM))
    networks:
      - laravel_network_dev
    volumes:
      - .:/var/www/html # copia do henriquedois(PC) para html(DOCKER)
    depends_on:
      - mysql #depende do banco pra subir

  mysql:
    container_name: banco-dev
    image: mysql:8.0 # imagem para o banco de dados
    environment: # variaveis de ambiente 
      MYSQL_DATABASE: 'henriquedb10' # nome do banco a ser usado
      MYSQL_USER: 'root'
      MYSQL_ROOT_PASSWORD: 'xxx' # senha do root
    #ports:
    #  - "3307:3306"
    networks:
      - laravel_network_dev
    healthcheck:
            test: ["CMD-SHELL", 'mysql -uroot --database=henriquedb10 --password=xxx --execute="SELECT count(table_name) > 0 FROM information_schema.tables;" --skip-column-names -B']
            interval: 10s
            timeout: 10s
            retries: 4
    volumes:
      - .docker/dbdata-dev:/var/lib/mysql/ 
      - ./mysql/my.cnf:/etc/mysql/my.cnf

#volumes:
#  dbdata:
#    driver: local
networks:
  laravel_network_dev:
    driver: bridge
pipeline {
    agent any
    
    stages {
        stage('Clone Repository') {
            steps {
                git branch: 'main', url: 'https://github.com/setmehemg/arq-software-uni.git'
            }
        }
        
        stage('Build Docker Image') {
            steps {
                sh 'docker build -t henriquemg/gcs-laravel:latest .'
            }
        }
        
        stage('Run Dev Environment') {
            steps {
                sh 'docker compose -f docker-compose.dev.yml -p dev up -d'
            }
        }
        
        stage('Execute Tests') {
            steps {
                sh 'docker exec eventos-dev php artisan migrate --force'
                sh 'docker exec eventos-dev php artisan db:seed --class=EventosTableSeeder'
                sh 'docker exec -t eventos-dev php artisan test'
            }
        }
        
        stage('Deploy to Docker Hub') {
            steps {
                script {
                        sh 'docker login -u xxx -p xxx'
                        sh 'docker push henriquemg/gcs-laravel:latest'
                    }
            }
        }
    }
}

的数据
我已经尝试过使用docker-compose.dev.yml来设置环境变量,但是效果不太好:

environment:
      - "APP_ENV=development"
      - "DB_CONNECTION=mysql"
      - "DB_HOST=mysql"
      - "DB_PORT=3306"
      - "DB_DATABASE=henriquedb10"
      - "DB_USERNAME=root"
      - "DB_PASSWORD=xxx"


并在docker compose命令上设置“--build-arg”,但效果不佳
更新1:我尝试将.env复制到jenkins工作区内的文件夹中,并在Jenkinsfile中使用以下代码,但也返回了一个错误。

stage("Populate .env file") {
            steps {
                dir("/var/lib/jenkins/workspace/envs/laravel") {
                    fileOperations([fileCopyOperation(excludes: '', flattenFiles: true, includes: '.env', targetLocation: "${WORKSPACE}")])
                }
            }
        }

omhiaaxx

omhiaaxx1#

你可以在整个管道中传递environ,然后用args传递给docker
你也可以在声明式的docker pipeline中隐藏任何文件:

stage('run dockerfile') {
        agent{
          dockerfile {
            label 'devops-docker' 
            registryUrl 'https://my_registry_url/'
            registryCredentialsId 'My_creds'
            args ARGS
           }
        }
        steps {
          sh returnStatus: true, script: './gradlew test --scan --tests "tests.*"'
          publishHTML( [
            allowMissing: true,
            alwaysLinkToLastBuild: true,
            keepAll: true,
            reportDir: "build/reports/tests/test",
            reportFiles: 'index.html',
            reportName: 'HTML Report',
            reportTitles: '',
            useWrapperFileDirectly: true])
          dir('allure results'){
            stash allowEmpty: true, includes: '**', name: 'allure_results'
          }
        }
    }
    post{
       always{
         unstash 'allure_results'
         sh 'ls'
       }
    }

字符串
注意。藏匿将由Jenkins代理帐户执行。请确保该文件具有正确的权限

相关问题