Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1K
Views
Cómo configurar la conexión a la base de datos MySql con gitlab CI/CD

Estoy tratando de configurar la prueba automática del proyecto django usando CI/CD gitlab. El problema es que no puedo conectarme a la base de datos Mysql de ninguna manera.

gitlab-ci.yml

 services: - mysql:5.7 variables: MYSQL_DATABASE: "db_name" MYSQL_ROOT_PASSWORD: "dbpass" MYSQL_USER: "username" MYSQL_PASSWORD: "dbpass" stages: - test test: stage: test before_script: - apt update -qy && apt-get install -qqy --no-install-recommends default-mysql-client - mysql --user=$MYSQL_USER --password=$MYSQL_PASSWORD --database=$MYSQL_DATABASE --host=$MYSQL_HOST --execute="SHOW DATABASES; ALTER USER '$MYSQL_USER'@'%' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'" script: - apt update -qy - apt install python3 python3-pip virtualenvwrapper -qy - virtualenv --python=python3 venv/ - source venv/bin/activate - pwd - pip install -r requirement.txt - python manage.py test apps

Con esta configuración de archivo, me sale error

 ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

¿Qué he tratado de hacer?

agregar a mysql script tcp conexión en lugar de socket

 mysql --protocol=TCP --user=$MYSQL_USER --password=$MYSQL_PASSWORD --database=$MYSQL_DATABASE --host=$MYSQL_HOST --execute="SHOW DATABASES; ALTER USER '$MYSQL_USER'@'%' IDENTIFIED WITH mysql_native_password BY '$MYSQL_PASSWORD'"

Y en este caso tengo

 ERROR 2002 (HY000): Can't connect to MySQL server on 'localhost' (99)

¿Cómo lo configuro correctamente?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Debe usar el nombre del servicio como nombre de host de la base de datos. En este caso, MYSQL_HOST debería ser mysql .

Puede ver un ejemplo en la página de Gitlab y leer sobre cómo los servicios están vinculados al trabajo

over 4 years ago · Santiago Trujillo Report

0

Puede haber varias razones para su problema:

  • Versión incorrecta de MySQL.
    • Solución: utilice mysql:5.7 en lugar de mysql:latest
  • Falta el servidor MySQL.
    • Solución: agregue MYSQL_HOST en las variables con el nombre de host del servidor MySQL. (Debería ser mysql al usar mysql:5.7 en la clave de services )
  • Django usa diferentes credenciales de DB.
    • Solución: verifique las credenciales en la sección de variables de su .gitlab-ci.yml y compárelas con la settings.py de Django.py . Deberían ser iguales.
  • Cliente MySQL no instalado.
    • Solución: instale mysql-client en la sección de secuencias de comandos y verifique si puede conectarse.

Aquí hay una secuencia de script de muestra que instala el cliente MySQL y se conecta a la base de datos en una imagen basada en Debian (o una imagen python:latest ):

 script: - apt-get update && apt-get install -y git curl libmcrypt-dev default-mysql- - mysql --version - sleep 20 - echo "SHOW tables;"| mysql -u root -p"$MYSQL_ROOT_PASSWORD" -h "${MYSQL_HOST}" "${MYSQL_DATABASE}"

Aquí hay un ejemplo completo y válido del uso de MySQL 5.7 como un servicio y una imagen de python con mysql-client instalado que se conecta correctamente a la base de datos MySQL:

 stages: - test variables: MYSQL_DATABASE: "db_name" MYSQL_ROOT_PASSWORD: "dbpass" MYSQL_USER: "username" MYSQL_PASSWORD: "dbpass" MYSQL_HOST: mysql test: image: python:latest stage: test services: - mysql:5.7 script: - apt-get update && apt-get install -y git curl libmcrypt-dev default-mysql-client - mysql --version - sleep 20 - echo "SHOW tables;" | mysql -u root -p"$MYSQL_ROOT_PASSWORD" -h "${MYSQL_HOST}" "${MYSQL_DATABASE}" - echo "Database host is '${MYSQL_HOST}'"
over 4 years ago · Santiago Trujillo Report

0

Veo que hay una respuesta aceptada pero con mysql 8.0 y python3:buster algunas cosas se rompieron. Las imágenes de Python Debian se envían con mariadb y no es fácil configurar los paquetes estándar de mysql-client, lo que da como resultado: "django.db.utils.OperationalError: 2059, "Complemento de autenticación"

Obtuve un YAML que funciona a continuación, usando Ubuntu como imagen base y mysql 8.0 como servicio. Puede usar el uso raíz tanto en .gitlab-ci como en test_settings o darle al usuario MYSQL los privilegios para crear nuevas bases de datos y modificar las existentes.

Las variables iniciales MYSQL_DB _USER y _PASS se pueden configurar en Gitlab en Configuración -> CI/CD -> Variables.

.gitlab-ci.yml:

 variables: # "When using a service (eg mysql) in the GitLab CI that needs environtment variables # to run, only variables defined in .gitlab-ci.yml are passed to the service and # variables defined in GitLab GUI are unavailable." # https://gitlab.com/gitlab-org/gitlab/-/issues/30178 # DJANGO_CONFIG: "test" MYSQL_DATABASE: $MYSQL_DB MYSQL_ROOT_PASSWORD: $MYSQL_PASS MYSQL_USER: $MYSQL_USER MYSQL_PASSWORD: $MYSQL_PASS # -- In your django settings file for the test environment you could put: # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.mysql', # 'NAME': os.environ.get('MYSQL_DATABASE'), # 'USER': os.environ.get('MYSQL_USER'), # 'PASSWORD': os.environ.get('MYSQL_PASSWORD'), # 'HOST': 'mysql', # 'PORT': '3306', # 'CONN_MAX_AGE':60, # }, # } # -- You could us '--settings' to specify a custom settings file on the command line # -- below or use an environment variable to trigger an include in your settings: # if os.environ.get('DJANGO_CONFIG')=='test': # from .settings_test import * # or specific overrides # default: image: ubuntu:20.04 # -- Pick zero or more services to be used on all builds. # -- Only needed when using a docker container to run your tests in. # -- Check out: http://docs.gitlab.com/ee/ci/docker/using_docker_images.html#what-is-a-service services: - mysql:8.0 # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache # cache: # paths: # - ~/.cache/pip/ before_script: - echo -e "Using Database $MYSQL_DB with $MYSQL_USER" - apt --assume-yes update - apt --assume-yes install apt-utils - apt --assume-yes install net-tools python3.8 python3-pip mysql-client libmysqlclient-dev # - apt --assume-yes upgrade - pip3 install -r requirements.txt djangotests: script: # -- The MYSQL user gets only permissions for MYSQL_DB and therefor cant create a test_db. - echo "GRANT ALL on *.* to '${MYSQL_USER}';"| mysql -u root --password="${MYSQL_ROOT_PASSWORD}" -h mysql # -- use python3 explicitly. see https://wiki.ubuntu.com/Python/3 - python3 manage.py test migrations: script: - python3 manage.py makemigrations - python3 manage.py makemigrations myapp - python3 manage.py migrate - python3 manage.py check
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!