Gitlab CI Symfony : SQLSTATE[HY000] [2002] Connection refused - php

I use gitlab to run unit tests each time someone push the code. I get this error during composer installation.
> Incenteev\ParameterHandler\ScriptHandler::buildParameters
Creating the "app/config/parameters.yml" file
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
> Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache
[Doctrine\DBAL\Exception\ConnectionException]
An exception occured in driver: SQLSTATE[HY000] [2002] Connection refused
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000] [2002] Connection refused
[PDOException]
SQLSTATE[HY000] [2002] Connection refused
Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-install-cmd event terminated with an exception
Here is my configuration :
.gitlab-ci.yml file
# Select image from https://hub.docker.com/_/php/
image: php:5.6
# Select what we should cache
cache:
paths:
- vendor/
before_script:
# Install ssh-agent if not already installed, it is required by Docker.
# (change apt-get to yum if you use a CentOS-based image)
- 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y )'
#
Run ssh-agent (inside the build environment)
- eval $(ssh-agent -s)
# Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
- ssh-add <(echo "$SSH_PRIVATE_KEY")
# For Docker builds disable host key checking. Be aware that by adding that
# you are suspectible to man-in-the-middle attacks.
# WARNING: Use this only with the Docker executor, if you use it with shell
# you will overwrite your user's SSH config.
- mkdir -p ~/.ssh
- '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config'
- cp ci/custom.ini /usr/local/etc/php/conf.d/custom.ini
- bash ci/docker_install.sh > /dev/null
# Install composer
- curl -sS https://getcomposer.org/installer | php
services:
- mysql:latest
variables:
# Configure mysql service (https://hub.docker.com/_/mysql/)
MYSQL_DATABASE: symfony
MYSQL_ROOT_PASSWORD: root
# We test PHP5.6 (the default) with MySQL
test:mysql:
script:
# Install all project dependencies
- php composer.phar install
- phpunit --coverage-text --colors=never -c app/
parameters.yml.dist
parameters:
database_host: 127.0.0.1
database_port: ~
database_name: symfony
database_user: root
database_password: root
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: ~
mailer_password: ~
# A secret key that's used to generate certain security-related tokens
secret: ThisTokenIsNotSoSecretChangeIt
database_slave1_host: 127.0.0.1
database_slave1_port: ~
database_slave1_name: symfony
database_slave1_user: root
database_slave1_password: root
I have read and follow the instruction of the gitlab website. Maybe my mistake is obvious, but I can't see it.

As you are using MySQL that is running in another container, you have to use its hostname, not 127.0.0.1. The correct database host should be "mysql". This is covered in one of the sections of the GitLab's documentation:
The service container for MySQL will be accessible under the hostname mysql. So, in order to access your database service you have to connect to the host named mysql instead of a socket or localhost.

One of the possible reasons for this error is that you attempt to access the database while it still initialises. This is covered in the MySQL's caveats section on the Docker HUB.
If there is no database initialised when the container starts, then a default database will be created. While this is the expected behaviour, this means that it will not accept incoming connections until such initialisation completes. This may cause issues when using automation tools...
A crude solution would be to use sleep command before you start any process that accesses database. You can add it to the before_script section:
before_script:
- sleep 60s
A better and more complex solution would be to probe the MySQL server, repeatedly checking whether it already accepts connections.

Related

Laravel won't connect to database server that set in .env file

I started a new Laravel 9.x + JsonApi project on docker-compose with 2 containters, 'web' and 'mysql'. Artisan migrations, seeding and db:show works fine. But when I'm trying to load a page from browser or Postman, it returns DB error
`SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo for mariadb failed: Temporary failure in name resolution
select * from redirects where redirects.id = 1 limit 1 `
The weird part is that my DB host is mysql and 'mariadb' string is never mentioned in my code (except some vendor files), nor in docker files, nor in .env file. I also checked container environment variables - nothing there.
Artisan scripts work fine.
Here are my settings, if it helps. Mariadb was never mentioned, it was mysql from the very beginning.
docker-compose.yml
version: "3.4"
services:
mysql:
image: mysql
volumes:
- mysql_db:/var/lib/mysql
ports:
- 3306:3306
environment:
- MYSQL_ROOT_PASSWORD=***
- MYSQL_DATABASE=url_shortener
web:
build:
dockerfile: Dockerfile.web.dev
context: .
#image: php:alpine
volumes:
- "./:/app"
- "/app/src/vendor"
- web_root_home:/root
working_dir: /app/src/
command: "php artisan serve --host=0.0.0.0 --port=7999"
ports:
- 8000:7999
depends_on:
- mysql
volumes:
mysql_db:
web_root_home:
Dockerfile.web.dev
#FROM php
FROM bitnami/laravel
WORKDIR /app/src/
COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer
ENV COMPOSER_ALLOW_SUPERUSER=1
RUN apt update
RUN apt install -y git build-essential vim mc mlocate
RUN pecl install xdebug
COPY ./src /app/src
COPY ./src/composer.json ./
COPY ./src/.env ./
RUN composer install
RUN php artisan key:generate
CMD ["php", "artisan", "serve", "--host=0.0.0.0", "--port=8000"]
.env (DB part)
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=url_shortener
DB_USERNAME=root
DB_PASSWORD=***
app/config/database.php wasn't changed
artisan db:show
root#a3c873713ee1:/app/src# php artisan db:show
MySQL 8 ...................................................................
Database .................................................... url_shortener
Host ................................................................ mysql
Port ................................................................. 3306
Username ............................................................. root
URL .......................................................................
Open Connections ........................................................ 3
Tables .................................................................. 6
Total Size ........................................................ 0.09MiB
Table .......................................................... Size (MiB)
redirects ............................................................ 0.02
failed_jobs .......................................................... 0.02
migrations ........................................................... 0.02
personal_access_tokens ............................................... 0.02
password_resets ...................................................... 0.02
users ................................................................ 0.02
migrations and seeding works fine, I can connect to mysql from the host laptop. All seeds data are there
I tried to clear config cache, didn't help
root#a3c873713ee1:/app/src# php artisan config:clear
INFO Configuration cache cleared successfully.
I also reloaded containers, no luck as well
Stack trace isn't useful error screenshot
I'm out of ideas what to try and where it takes this mariadb host at all.
I could solve the problem by defining the DATABASE_URL=mysql://root:PASSWORD#mysql/url_shortener in my .env file. I still have no idea where it got mariaDB host from.

Laravel laradock Unable to connect localhost

After installing Docker in ubuntu and adding laradock to an existing project, I run this below command to start using laradock:
docker-compose up -d nginx mysql phpmyadmin workspace
result:
Creating laradock_mysql_1 ... done
Creating laradock_docker-in-docker_1 ... done
Creating laradock_workspace_1 ... done
Creating laradock_phpmyadmin_1 ... done
Creating laradock_php-fpm_1 ... done
Creating laradock_nginx_1 ... done
now after running docker-compose exec bash command I served laravel into that
docker-compose exec workspace bash
root#b3c88be3e389:/var/www# php artisan serve
INFO Server running on [http://127.0.0.1:8000].
Press Ctrl+C to stop the server
when I clicked on IP address, I get this message in browser:
Unable to connect
Firefox can’t establish a connection to the server at 127.0.0.1:8000.
The site could be temporarily unavailable or too busy. Try again in a few moments.
If you are unable to load any pages, check your computer’s network connection.
If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the web.
docker-compose ps command result:
Name Command State Ports
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
laradock_docker-in-docker_1 dockerd-entrypoint.sh Up 2375/tcp, 2376/tcp
laradock_mysql_1 docker-entrypoint.sh mysqld Up 0.0.0.0:3306->3306/tcp,:::3306->3306/tcp, 33060/tcp
laradock_nginx_1 /docker-entrypoint.sh /bin ... Up 0.0.0.0:443->443/tcp,:::443->443/tcp, 0.0.0.0:80->80/tcp,:::80->80/tcp, 0.0.0.0:81->81/tcp,:::81->81/tcp
laradock_php-fpm_1 docker-php-entrypoint php-fpm Up 9000/tcp
laradock_phpmyadmin_1 /docker-entrypoint.sh apac ... Up 0.0.0.0:8081->80/tcp,:::8081->80/tcp
laradock_workspace_1 /sbin/my_init Up 0.0.0.0:2222->22/tcp,:::2222->22/tcp, 0.0.0.0:3000->3000/tcp,:::3000->3000/tcp, 0.0.0.0:3001->3001/tcp,:::3001->3001/tcp,
0.0.0.0:4200->4200/tcp,:::4200->4200/tcp, 0.0.0.0:5173->5173/tcp,:::5173->5173/tcp, 0.0.0.0:8001->8000/tcp,:::8001->8000/tcp,
0.0.0.0:8080->8080/tcp,:::8080->8080/tcp
nginx definition into docker-compose.yml:
nginx:
build:
context: ./nginx
args:
- CHANGE_SOURCE=${CHANGE_SOURCE}
- PHP_UPSTREAM_CONTAINER=${NGINX_PHP_UPSTREAM_CONTAINER}
- PHP_UPSTREAM_PORT=${NGINX_PHP_UPSTREAM_PORT}
- http_proxy
- https_proxy
- no_proxy
volumes:
- ${APP_CODE_PATH_HOST}:${APP_CODE_PATH_CONTAINER}${APP_CODE_CONTAINER_FLAG}
- ${NGINX_HOST_LOG_PATH}:/var/log/nginx
- ${NGINX_SITES_PATH}:/etc/nginx/sites-available
- ${NGINX_SSL_PATH}:/etc/nginx/ssl
ports:
- "${NGINX_HOST_HTTP_PORT}:80"
- "${NGINX_HOST_HTTPS_PORT}:443"
- "${VARNISH_BACKEND_PORT}:81"
depends_on:
- php-fpm
networks:
- frontend
- backend
and nginx Dockerfile:
FROM nginx:alpine
LABEL maintainer="Mahmoud Zalt <mahmoud#zalt.me>"
COPY nginx.conf /etc/nginx/
# If you're in China, or you need to change sources, will be set CHANGE_SOURCE to true in .env.
ARG CHANGE_SOURCE=false
RUN if [ ${CHANGE_SOURCE} = true ]; then \
# Change application source from dl-cdn.alpinelinux.org to aliyun source
sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/' /etc/apk/repositories \
;fi
RUN apk update \
&& apk upgrade \
&& apk --update add logrotate \
&& apk add --no-cache openssl \
&& apk add --no-cache bash
RUN apk add --no-cache curl
RUN set -x ; \
addgroup -g 82 -S www-data ; \
adduser -u 82 -D -S -G www-data www-data && exit 0 ; exit 1
ARG PHP_UPSTREAM_CONTAINER=php-fpm
ARG PHP_UPSTREAM_PORT=9000
# Create 'messages' file used from 'logrotate'
RUN touch /var/log/messages
# Copy 'logrotate' config file
COPY logrotate/nginx /etc/logrotate.d/
# Set upstream conf and remove the default conf
RUN echo "upstream php-upstream { server ${PHP_UPSTREAM_CONTAINER}:${PHP_UPSTREAM_PORT}; }" > /etc/nginx/conf.d/upstream.conf \
&& rm /etc/nginx/conf.d/default.conf
ADD ./startup.sh /opt/startup.sh
RUN sed -i 's/\r//g' /opt/startup.sh
CMD ["/bin/bash", "/opt/startup.sh"]
EXPOSE 80 81 443
laradock env:
# All volumes driver
VOLUMES_DRIVER=local
# All Networks driver
NETWORKS_DRIVER=bridge

Connect PHP to Postgresql on OpenBSD

I have PHP and Postgresql installed on OpenBSD 7.0 (VPS). PHP is working (I can echo from an index.php file). And my Postgresql server is running (I can connect and create tables from the command line) but I can't get PHP to connect.
I suspect it has something to do with PHP not being able to access the DB socket (because it operates in chroot). Or it's related to my postgresql.conf not using "localhost" (explained below). But I'm not lost on trying to solve for those.
/etc/httpd.conf
(port 80 blocks are also there and redirect to 443)
server "db.example.com" {
listen on * tls port 443
root "/htdocs/db"
directory index index.php
authenticate with ".htpasswd"
tls {
certificate "/etc/ssl/db.example.com.fullchain.pem"
key "/etc/ssl/private/db.example.com.key"
}
location "*.php" {
fastcgi socket "/run/php-fpm.sock"
}
}
(and /etc/acme-client.conf is aligned and certificate installed)
PHP install
# pkg_add php php-pgsql (version 8 selected)
# rcctl enable php80_fpm
# rcctl start php80_fpm
# rcctl restart httpd
Postgres (part 1)
# pkg_add postgresql-server postgresql-contrib
# su - _postgresql
$ mkdir /var/postgresql/data
$ initdb -D /var/postgresql/data -U postgres -A scram-sha-256 -E UTF-8 -W
[password created]
Postgres (part 2)
/var/postgresql/data/postgresql.conf
(Localhost doesn't resolve to my VPS IP so I add my actual IP here)
listen_addresses = '123.45.67.89'
Postgres (part 3)
$ pg_ctl -D /var/postgresql/data -l logfile start
$ exit
# rcctl enable postgresql
# rcctl start postgresql
# psql -U postgres
# CREATE DATABASE test;
# CREATE USER tester WITH PASSWORD '12345';
# GRANT ALL PRIVILEGES ON DATABASE test TO tester;
/var/www/htdocs/db/index.php
<?php
echo "Hello world!"; (this part works, then no output after this)
$db = pg_connect("host=123.45.67.89 port=5432 dbname=test user=tester password=12345");
if ($db) {
echo "I'm in.";
} else {
echo "No luck.";
}
?>
Did you activate the PG PHP module by copying or symlinking its .ini file to /etc/php-8.0/? If not, take a look at the "Extension modules" section of /usr/local/share/doc/pkg-readmes/php-8.0:
For all extensions packaged separately (and for opcache), you will
find a file named /etc/php-8.0.sample/(MODULE_NAME).ini. To enable it,
add a symlink into /etc/php-8.0 and restart:
ln -sf ../php-8.0.sample/MODULE_NAME.ini /etc/php-8.0/
To disable, remove the symlink from /etc/php-8.0 and restart:
rm /etc/php-8.0/MODULE_NAME.ini
If you have installed a number of extensions and wish to enable them
all, you can use these shell commands:
# cd /etc/php-8.0.sample
# for i in *; do ln -sf ../php-8.0.sample/$i ../php-8.0/; done
After enabling or disabling extensions (or otherwise modifying php's
configuration), use rcctl(8) to restart php80_fpm or Apache.

Docker MYSQL '[2002] Connection refused'

I was trying out Docker for the first time. Got a LEMP stack up and running, but I can't connect to the MYSQL Database. Not on my Symfony application, not on PHPMyAdmin. The applications are returning the following error code:
An exception occured in driver: SQLSTATE[HY000] [2002] Connection refused
This is my docker-compose.yml:
nginx:
image: tutum/nginx
ports:
- "80:80"
links:
- phpfpm
volumes:
- ./nginx/default:/etc/nginx/sites-available/default
- ./nginx/default:/etc/nginx/sites-enabled/default
- ./logs/nginx-error.log:/var/log/nginx/error.log
- ./logs/nginx-access.log:/var/log/nginx/access.log
phpfpm:
build: phpfpm/
ports:
- "9000:9000"
volumes:
- ./public:/usr/share/nginx/html
mysql:
image: mariadb
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: admin
phpmyadmin:
image: phpmyadmin/phpmyadmin
restart: always
links:
- mysql
ports:
- 8183:80
environment:
MYSQL_USERNAME: admin
MYSQL_ROOT_PASSWORD: admin
PMA_ARBITRARY: 1
Dockerfile PHPFPM:
FROM php:fpm
RUN docker-php-ext-enable opcache
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq-dev \
&& docker-php-ext-install mysqli pdo_pgsql pdo_mysql
GitHub URL: https://github.com/MolengraafFrank/DockerSymfony
Could someone help me out? Thank you for your time.
The '[2002] Connection refused' means you can reach the database server, but you don't have right access for the user (in your case admin). By default mariadb have a root user with the password given by MYSQL_ROOT_PASSWORD and this user can connect from any server (%).
If you want use an over login to your databases, you have to create it in the databases server with the right granting on databases from chosen locations.
The problem here is that you have named your database server as 'mysql' (service name in the docker-compose file). But by default phpmyadmin tries to connect to a database server named 'db'. Adding PMA_HOST: mysql under the environment section of the phpmyadmin service will resolve this problem.
I think that MYSQL_USERNAME and PMA_ARBITRARY are useless if you work with default configuration (connection with root to your databases server)
I had this challenge because I am running 3 different containers with different IP Addresses
db - 172.18.0.3 - container for MYSQL
app - 172.18.0.2 - container for Laravel app
so I fixed it by editing my Laravel .env file
DB_CONNECTION=mysql
DB_HOST=172.18.0.3
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
...
To get your containers Ip addresses. From your docker host
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
UPDATED:
For latest docker versions and based on the services name, "mysql", in your docker-compose.yml
mysql:
image: mariadb
ports:
- 3306:3306
You can try this:
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
DB_HOST is the name of MySQL service name defined in docker-compose.yml
I've managed to connect to the mysql instance using mysql command line tool, this is the command I used - mysql -u root -p -h 127.0.0.1, and the entering the admin password. Is that a sufficient solution for you?
In my case I was running mysql in a docker container whose port was mapped to the host mac (3306:3306). I tried connecting to this database from a phpmyadmin docker container using 127.0.0.1 . But it won't work because the localhost on the phpmyadmin docker container does not have the required mysql running.
To connect to the host from docker network
docker.for.mac.host.internal
Docker Networking Docker Compose Networking
For my instance, the issue was with port mapping somehow.
In my case it was 3307:3306, as soon as I changed it to 3307 on the right side as well, I could connect to the DB instance.
Adding DB_READ_HOST=db solved this problem for me
If you want to know why your connexion failed, you can use in your terminal php artisan tinker and then
like
DB::connection()->getPdo();
Unfortunately this will only give you a part of the error.
Quit tinker and then use this command php artisan db will give you more information like database type, host, port, ad user about the issue.
Like this one
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (61)
Symfony\Component\Process\Exception\ProcessFailedException
The command "'mysql' '--host=127.0.0.1' '--port=3306' '--user=root' '--default-character-set=utf8mb4' 'laravel'" failed.
Exit Code: 1(General error)
Working directory: /Users/Dev/Documents/www/laravel_docker/src/addressAPI
Output:
================
Error Output:
================
at vendor/symfony/process/Process.php:270
266▕ */
267▕ public function mustRun(callable $callback = null, array $env = []): self
268▕ {
269▕ if (0 !== $this->run($callback, $env)) {
➜ 270▕ throw new ProcessFailedException($this);
271▕ }
272▕
273▕ return $this;
274▕ }
+14 vendor frames
15 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
This will not give you the answer on what is wrong, but at least you can understand why your config is wrong.
you need to link the phpfpm container to mysql.

Symfony2 Database Config

I've just inherited a Symfony2 project from a former co-worker. I'm trying to get it running locally, but am getting a SQLSTATE[HY000] [2002] Connection refused error. I guess I'm missing the database connection that I've read should be in the app/config/parameters.yml file.
Is there anyway of finding this information if all I have is the project and the live site?
If it's standard Symfony2 project you have to configure your database connection information in app/config/parameters.yml, like:
# app/config/parameters.yml
parameters:
database_driver: pdo_mysql
database_host: localhost
database_name: test_project
database_user: root
database_password: password
# ...
More in doc.
After that you have to create database:
$ php app/console doctrine:database:create
Next, create table schema:
$ php app/console doctrine:schema:update --force
Also, you could load (if your co-worker provided it ; ) some data fixtures, so try:
$ php app/console doctrine:fixtures:load
If your coworker doesn't use doctrine fixtures you should consider dumping data from your prod database.

Categories