How to connect Vagrant wordpress VM to a DB one - mysql

I want to connect a vagrant vm that installs WordPress and a SQL machine that installs MySQL server and I can't get it done. Anything would help. I basically wanna go in the web1 IP and have the WordPress. Now I get "Error establishing database connection". My Vagrantfile is this one:
( I want to connect web1 and db right now )
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "generic/ubuntu2010"
# Web 1 - 192.168.33.10
config.vm.define "web1" do |web1|
web1.vm.provider "virtualbox" do |vb|
vb.name = "web1"
vb.memory = "1024"
end
web1.vm.hostname = "web1"
web1.vm.network "private_network", ip: "192.168.33.10"
web1.vm.network "forwarded_port", guest: 80, host: 8080
web1.vm.synced_folder "web1_wordpress", "/var/www/html"
web1.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apache2 php php-mysql
cd /var/www/html
wget -c http://wordpress.org/latest.zip
unzip latest.zip
mv wordpress/* .
rm index.html
touch wp-config.php
cp wp-config-sample.php wp-config.php
sed -i 's/database_name_here/wordpress/' wp-config.php
sed -i 's/username_here/wpuser/' wp-config.php
sed -i 's/password_here/wppass/' wp-config.php
SHELL
end
# Web 2 -192.168.33.20
config.vm.define "web2" do |web2|
web2.vm.provider "virtualbox" do |vb|
vb.name = "web2"
vb.memory = "1024"
end
web2.vm.hostname = "web2"
web2.vm.network "private_network", ip: "192.168.33.20"
web2.vm.network "forwarded_port", guest: 80, host: 8081
web2.vm.synced_folder "web2_wordpress", "/var/www/html"
web2.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apache2 php php-mysql
cd /var/www/html
wget -c http://wordpress.org/latest.zip
unzip latest.zip
mv wordpress/* .
rm index.html
touch wp-config.php
cp wp-config-sample.php wp-config.php
sed -i 's/database_name_here/wordpress/' wp-config.php
sed -i 's/username_here/wpuser/' wp-config.php
sed -i 's/password_here/wppass/' wp-config.php
SHELL
end
# DB - 192.168.33.30
config.vm.define "db" do |db|
db.vm.provider "virtualbox" do |vb|
vb.name = "db"
vb.memory = "1024"
end
db.vm.hostname = "db"
db.vm.network "private_network", ip: "192.168.33.30"
db.vm.provision "shell", inline: <<-SHELL
apt update
apt install -y mysql-server
mysql -u root -e "CREATE DATABASE wordpress;"
mysql -u root -e "CREATE USER 'wpuser'#'localhost' IDENTIFIED BY 'wppass';"
mysql -u root -e "GRANT ALL ON wordpress.* TO 'wpuser'#'localhost';"
SHELL
end
# LB - 192.168.33.40
config.vm.define "lb" do |lb|
lb.vm.provider "virtualbox" do |vb|
vb.name = "lb"
vb.memory = "1024"
end
lb.vm.hostname = "lb"
lb.vm.network "private_network", ip: "192.168.33.40"
lb.vm.network "forwarded_port", guest: 80, host: 80
lb.vm.provision "shell", inline: <<-SHELL
apt update
apt install -y haproxy
SHELL
end
end

Related

I can't do mysql php artisan migrations in my docker compose. Error SQLSTATE[HY000] [2002]

I'm currently developing a laravel-vue-mysql environment with docker compose.
I took as guide these articles link link
My docker compose is working fine the web and app services are working good and its deploy as it should. But i can't configure my db.
I'm try executing docker-compose exec app php artisan migrate but I have SQLSTATE no such file or directory exception, I'm been stuck for 3 days in this.
I've read all comments about this problem but could get solution. I have given all privileges to root user in my db. I have tried changing my dbhost with my container ip or container db name, I have tried changing database.php host for my db name too but it didn't work either.
I think my error could be in my "unix_socket' => '/var/run/mysqld/mysqld.sock',"
I'd like to clarify this route i got it through log in my docker mysql service and put a command in my db. I don't know if i have to put mysql.lock local route
which is /tmp/mysql.sock
Or it could be my database_url route, I'm not sure what i'm doing wrong. Need some help.
I want to create the data tables in my mysql docker service
This is my docker-compose.yml
version: '2'
services:
# The Application
app:
build:
context: ./
dockerfile: app.dockerfile
container_name: app
working_dir: /var/www
volumes:
- ./:/var/www
environment:
- "DB_PORT=3306"
- "DB_HOST=database"
# The Web Server
web:
build:
context: ./
dockerfile: web.dockerfile
container_name: web
working_dir: /var/www
volumes_from:
- app
ports:
- 8080:80
# The Database
database:
build:
context: ./
dockerfile: db.dockerfile
image: mysql:5.7
container_name: db
environment:
- "MYSQL_DATABASE=homestead"
- "MYSQL_USER=root"
- "MYSQL_PASSWORD=secret"
- "MYSQL_ROOT_PASSWORD=secret"
volumes:
- dbdata:/var/lib/mysql
ports:
- "33061:3306"
#Volumes
volumes:
dbdata:
app.dockerfile
FROM php:7.3-fpm
# Update packages
RUN apt-get update
# Install PHP and composer dependencies
RUN apt-get install -qq git curl libmcrypt-dev libjpeg-dev libpng-dev libfreetype6-dev libbz2-dev
# Clear out the local repository of retrieved package files
# RUN apt-get clean
# Install needed extensions
# Here you can install any other extension that you need during the test and deployment process
RUN apt-get -y install libzip-dev
RUN pecl install mcrypt-1.0.3
RUN docker-php-ext-enable mcrypt
RUN apt-get clean; docker-php-ext-install pdo pdo_mysql zip gd pcntl opcache bcmath
# Installs Composer to easily manage your PHP dependencies.
RUN curl --silent --show-error https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Install Node
RUN apt-get update &&\
apt-get install -y --no-install-recommends gnupg &&\
curl -sL https://deb.nodesource.com/setup_10.x | bash - &&\
apt-get update &&\
apt-get install -y --no-install-recommends nodejs &&\
npm config set registry https://registry.npm.taobao.org --global &&\
npm install --global gulp-cli
CMD php-fpm
db.dockerfile
FROM mysql:5.7
# Setup the custom configuration
ADD my.cnf /mysql/mysql.conf.d/my.cnf
web.dockerfile
FROM nginx:1.10
ADD vhost.conf /etc/nginx/conf.d/default.conf
WORKDIR /var/www
.env
DB_CONNECTION=mysql
DB_HOST=database
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=root
DB_PASSWORD=secret
DATABASE_URL=mysql://root:#database:33061/homestead
vhost.config
server {
listen 80;
index index.php index.html;
root /var/www/public;
location / {
try_files $uri /index.php?$args;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass app:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
This is my .cnf
[mysqld]
# Accept connections from any IP address
general_log = 1
general_log_file = /var/lib/mysql/general.log
bind-address = 0.0.0.0
socket= /var/run/mysqld/mysqld.sock
#skip-grant-tables
This is my app/config/database.php
'mysql' => [
'driver'=>'mysql',
'url'=>env('DATABASE_URL'),
'host'=>env('DB_HOST','database'),
'port'=>env('DB_PORT','3306'),
'database'=>env('DB_DATABASE', 'forge'),
'username'=>env('DB_USERNAME', 'forge'),
'password'=>env('DB_PASSWORD', ''),
'unix_socket'=>'/var/run/mysqld/mysqld.sock',
'charset'=>'utf8mb4',
'collation'=>'utf8mb4_unicode_ci',
'prefix'=>'',
'prefix_indexes'=>true,
'strict'=>true,
'engine'=> null,
'options'=> extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA =>env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
When i try to migrate the mysql database it's return me this error:
Illuminate\Database\QueryException : SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = homestead and table_name = migrations and table_type = 'BASE TABLE')
at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669
665| // If an exception occurs when attempting to run a query, we'll format the error
666| // message to include the bindings with SQL, which will make this exception a
667| // lot more helpful to the developer instead of just the database's errors.
668| catch (Exception $e) {
> 669| throw new QueryException(
670| $query, $this->prepareBindings($bindings), $e
671| );
672| }
673|
Exception trace:
1 Doctrine\DBAL\Driver\PDOException::("SQLSTATE[HY000] [2002] No such file or directory")
/var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31
2 PDOException::("SQLSTATE[HY000] [2002] No such file or directory")
/var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27
3 PDO::__construct("mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=homestead", "root", "secret", [])
/var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27
4 Doctrine\DBAL\Driver\PDOConnection::__construct("mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=homestead", "root", "secret", [])
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:67
5 Illuminate\Database\Connectors\Connector::createPdoConnection("mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=homestead", "root", "secret", [])
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:46
6 Illuminate\Database\Connectors\Connector::createConnection("mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=homestead", [])
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/MySqlConnector.php:24
7 Illuminate\Database\Connectors\MySqlConnector::connect()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php:182
8 Illuminate\Database\Connectors\ConnectionFactory::Illuminate\Database\Connectors\{closure}()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:924
9 call_user_func(Object(Closure))
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:924
10 Illuminate\Database\Connection::getPdo()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:959
11 Illuminate\Database\Connection::getReadPdo()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:404
12 Illuminate\Database\Connection::getPdoForSelect()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:330
13 Illuminate\Database\Connection::Illuminate\Database\{closure}("select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'")
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:662
14 Illuminate\Database\Connection::runQueryCallback("select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'", Object(Closure))
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:629
15 Illuminate\Database\Connection::run("select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'", Object(Closure))
/var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:338
16 Illuminate\Database\Connection::select("select * from information_schema.tables where table_schema = ? and table_name = ? and table_type = 'BASE TABLE'")
/var/www/vendor/laravel/framework/src/Illuminate/Database/Schema/MySqlBuilder.php:18
17 Illuminate\Database\Schema\MySqlBuilder::hasTable("migrations")
/var/www/vendor/laravel/framework/src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php:169
18 Illuminate\Database\Migrations\DatabaseMigrationRepository::repositoryExists()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:590
19 Illuminate\Database\Migrations\Migrator::repositoryExists()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:91
20 Illuminate\Database\Console\Migrations\MigrateCommand::prepareDatabase()
/var/www/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php:63
21 Illuminate\Database\Console\Migrations\MigrateCommand::handle()
/var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32
22 call_user_func_array([])
/var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:32
23 Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
/var/www/vendor/laravel/framework/src/Illuminate/Container/Util.php:36
24 Illuminate\Container\Util::unwrapIfClosure(Object(Closure))
/var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:90
25 Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Object(Closure))
/var/www/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php:34
26 Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), [])
/var/www/vendor/laravel/framework/src/Illuminate/Container/Container.php:590
27 Illuminate\Container\Container::call()
/var/www/vendor/laravel/framework/src/Illuminate/Console/Command.php:134
28 Illuminate\Console\Command::execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
/var/www/vendor/symfony/console/Command/Command.php:255
29 Symfony\Component\Console\Command\Command::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
/var/www/vendor/laravel/framework/src/Illuminate/Console/Command.php:121
30 Illuminate\Console\Command::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
/var/www/vendor/symfony/console/Application.php:1001
31 Symfony\Component\Console\Application::doRunCommand(Object(Illuminate\Database\Console\Migrations\MigrateCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
/var/www/vendor/symfony/console/Application.php:271
32 Symfony\Component\Console\Application::doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
/var/www/vendor/symfony/console/Application.php:147
33 Symfony\Component\Console\Application::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
/var/www/vendor/laravel/framework/src/Illuminate/Console/Application.php:93
34 Illuminate\Console\Application::run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
/var/www/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:131
35 Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
/var/www/artisan:37
First of all if you perform docker exec app env | grep -e DB_ -e DATABASE, you will see only
DB_PORT=3306
DB_HOST=database
This is due to .env file purpose. If you want other variables to be set in you container at running stage, just pass them by this way:
version: '2'
services:
# The Application
app:
...
environment:
- DB_CONNECTION=${DB_CONNECTION}
- DB_HOST=${DB_HOST}
- DB_PORT=${DB_PORT}
- DB_DATABASE=${DB_DATABASE}
- DB_USERNAME=${DB_USERNAME}
- DB_PASSWORD=${DB_PASSWORD}
- DATABASE_URL=${DATABASE_URL}
And now
docker exec app env | grep -e DB_ -e DATABASE
DB_CONNECTION=mysql
DB_HOST=database
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=root
DB_PASSWORD=secret
DATABASE_URL=mysql://root:#database:33061/homestead
your app container knows how to communicate with your DB

Connection refused when trying to connect to local mysql database from docker container

I have a problem to connect with local mysql database from a docker container. I'm using docker-compose with two services in containers, database is not on container
I have this docker-compose file:
version: '2'
services:
web:
build:
context: ./
dockerfile: web-dev.dockerfile
volumes:
- ./:/var/www
ports:
- "8080:80"
links:
- app
network_mode: "bridge"
dns:
- 10.0.50.6
app:
build:
context: ./
dockerfile: app-dev.dockerfile
volumes:
- ./:/var/www
network_mode: "bridge"
dns:
- 10.0.50.6
the web container is an nginx service with this Dockerfile:
FROM nginx:1.10
ADD ./vhost.dev.conf /etc/nginx/conf.d/default.conf
WORKDIR /var/www
and this configuration file:
server {
listen 80;
index index.php index.html;
root /var/www/formapp/public;
location / {
try_files $uri /index.php?$args;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass app:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
the app container is an app service with this Dockerfile:
FROM php:7-fpm
ENV USER=pasquale
RUN apt-get update && apt-get install -y libmcrypt-dev mysql-client \
openssl zip unzip git nano wget libaio-dev iputils-ping
RUN mkdir -p /opt/oracle/instantclient_10_2
# Download files from in oracle folder:
# https://agora.zanichelli.it/downloads/basic-10.2.0.5.0-linux-x64.zip
# https://agora.zanichelli.it/downloads/sdk-10.2.0.5.0-linux-x64.zip
ADD oracle/basic-10.2.0.5.0-linux-x64.zip /opt/oracle/basic-10.2.0.5.0-linux-x64.zip
ADD oracle/sdk-10.2.0.5.0-linux-x64.zip /opt/oracle/sdk-10.2.0.5.0-linux-x64.zip
RUN unzip /opt/oracle/basic-10.2.0.5.0-linux-x64.zip -d /opt/oracle \
&& unzip /opt/oracle/sdk-10.2.0.5.0-linux-x64.zip -d /opt/oracle \
&& ln -s /opt/oracle/instantclient_10_2/libclntsh.so.10.1 /opt/oracle/instantclient_10_2/libclntsh.so \
&& ln -s /opt/oracle/instantclient_10_2/libclntshcore.so.10.1 /opt/oracle/instantclient_10_2/libclntshcore.so \
&& ln -s /opt/oracle/instantclient_10_2/libocci.so.10.1 /opt/oracle/instantclient_10_2/libocci.so
ADD oracle/tns-admin/tnsnames.ora /opt/oracle/instantclient_10_2/network/admin/tnsnames.ora
ENV LD_LIBRARY_PATH /opt/oracle/instantclient_10_2/
RUN docker-php-ext-install pdo_mysql \
&& pecl install mcrypt-1.0.1 \
&& docker-php-ext-enable mcrypt \
&& pecl install mongodb \
&& docker-php-ext-enable mongodb \
&& docker-php-ext-configure pdo_oci --with-pdo-oci=instantclient,/opt/oracle/instantclient_10_2,10.2 \
&& echo 'instantclient,/opt/oracle/instantclient_10_2' | pecl install oci8 \
&& docker-php-ext-install pdo_oci \
&& docker-php-ext-enable oci8
RUN yes | pecl install xdebug \
&& echo "zend_extension=$(find /usr/local/lib/php/extensions/ -name xdebug.so)" > /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_enable=1' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.default_enable=1' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_connect_back=1' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_autostart=1' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_handler="dbgp"' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_port=9000' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_host=0.0.0.0' >> /usr/local/etc/php/conf.d/xdebug.ini \
&& echo 'xdebug.remote_log=/var/www/xdebug.log' >> /usr/local/etc/php/conf.d/xdebug.ini
RUN mkdir -p /home/$USER
RUN groupadd -g 1000 $USER
RUN useradd -u 1000 -g $USER $USER -d /home/$USER
RUN chown $USER:$USER /home/$USER
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
WORKDIR /var/www
USER $USER
launching the containers with docker-compose -f docker-compose.dev.yml up --build -d works fine and docker ps command give me this output:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
7202e2862ef5 190todb_web "nginx -g 'daemon of…" 9 hours ago Up About an hour 443/tcp, 0.0.0.0:8080->80/tcp 190todb_web_1_3c628ae1c69b
d45c04d353d5 190todb_app "docker-php-entrypoi…" 9 hours ago Up About an hour 9000/tcp 190todb_app_1_dd2ac7028b87
I install a lumen app in my project folder formapp and then I created a seeder to insert fake data in my database, and from bash, if I run /projectfolder/formapp$ php artisan db:seed the seeder works and I have this output:
Seeding: UsersTableSeeder
Database seeding completed successfully.
Then I created a route to access my users table from the lumen app:
$router->get('users', function () use ($router) {
return User::all();
});
my lumen env file is this:
APP_NAME=Lumen
APP_ENV=local
APP_KEY=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
APP_DEBUG=true
APP_URL=http://localhost
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=form_db
DB_USERNAME=root
DB_PASSWORD=radiohead
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
JWT_SECRET=JhbGciOiJIUzI1N0eXAiOiJKV1QiLC
but if I try to connect from http://localhost:8080/users I have this lumen error:
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `users`)
I tried to change the DB_HOST but I cannot solve the problem:
0.0.0.0 (SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `users`));
172.17.0.1 (SQLSTATE[HY000] [1130] Host '172.17.0.2' is not allowed to connect to this MySQL server (SQL: select * from `users`));
172.17.0.1 is my docker0 inet address.
How can I config my project to work?
PS: the lumen app is up and running, is only the db connection that is not working
You cannot use localhost when the database and app are not on the same server.
You need to allow access by something like:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'172.17.0.2' IDENTIFIED BY '<password>';
You can replace 172.17.0.2 by wildcard %.

django cannot connect mysql in docker-compose

I'm very new for docker, now I am trying to run django with mariadb in docker through docker-compose, but I always get this error:
I use Docker version 17.09.1-ce, build 19e2cf6, docker-compose version 1.18.0, build 8dd22a9
django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL
server on \'mariadb55\' (111 "Connection refused")')
I can connect db correctly after run docker-compose up db in local or remote, and I even can run python manage.py runserver 0.0.0.0:6001 correctly in anaconda virtual environment to connect db service in docker by setting parameters of settings.py file like below:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'belter',
# 'HOST': 'mariadb55',
'HOST': '127.0.0.1',
'PORT': '3302',
'PASSWORD': 'belter_2017',
'default-character-set': 'utf8',
'OPTIONS': {
'sql_mode': 'traditional',
}
}
}
This is my docker-compose.yml file
version: '3'
services:
db:
image: mariadb:5.5
restart: always
environment:
- MYSQL_HOST=localhost
- MYSQL_PORT=3306
- MYSQL_ROOT_HOST=%
- MYSQL_DATABASE=test
- MYSQL_USER=belter
- MYSQL_PASSWORD=belter_2017
- MYSQL_ROOT_PASSWORD=123456_abc
volumes:
- /home/belter/mdbdata/mdb55:/var/lib/mysql
ports:
- "3302:3306"
web:
image: onlybelter/django_py35
command: python3 manage.py runserver 0.0.0.0:6001
volumes:
- /mnt/data/www/mysite:/djcode
ports:
- "6001:6001"
depends_on:
- db
links:
- db:mariadb55
I almost tried everything I can find, but still cannot figure it out, any help would be nice!
What I have tried:
Docker compose mysql connection failing
Linking django and mysql containers using docker-compose
Django connection to postgres by docker-compose
Finally, I figured it out!
The key point is, just as #SangminKim said, I need to use 3306 not 3302 in settings.py, and use db as HOST not 127.0.0.1.
So this is my docker-compose.yml file now:
version: '3'
services:
db:
image: mariadb:5.5
restart: always
environment:
- MYSQL_HOST=localhost
- MYSQL_PORT=3306 # cannot change this port to other number
- MYSQL_ROOT_HOST=%
- MYSQL_DATABASE=test
- MYSQL_USER=belter
- MYSQL_PASSWORD=belter_2017
- MYSQL_ROOT_PASSWORD=123456_abc
volumes:
- /home/belter/mdbdata/mdb55:/var/lib/mysql
ports:
- "3302:3306"
web:
image: onlybelter/django_py35
command: python3 manage.py runserver 0.0.0.0:6001
volumes:
- .:/djcode
ports:
- "6001:6001"
depends_on:
- db
So now we can connect this docker-mysql by mysql -h 127.0.0.1 -P 3302 -u root -p in shell directly, but we have to use db and 3306 in django settings.py file:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'belter',
# 'HOST': 'mariadb55',
'HOST': 'db', #<---
'PORT': '3306', #<---
'PASSWORD': 'belter_2017',
'default-character-set': 'utf8',
'OPTIONS': {
'sql_mode': 'traditional',
}
}
}
And we can still check if this port is open, by running extra command in docker-compose.yml file:
...
web:
image: onlybelter/django_py35
command: /bin/sh -c "python check_db.py --service-name mysql --ip db --port 3306"
volumes:
- .:/djcode
...
Here is check_db.py file:
# check_db.py
import socket
import time
import argparse
""" Check if port is open, avoid docker-compose race condition """
parser = argparse.ArgumentParser(description='Check if port is open, avoid\
docker-compose race condition')
parser.add_argument('--service-name', required=True)
parser.add_argument('--ip', required=True)
parser.add_argument('--port', required=True)
args = parser.parse_args()
# Get arguments
service_name = str(args.service_name)
port = int(args.port)
ip = str(args.ip)
# Infinite loop
while True:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, port))
if result == 0:
print("{0} port is open! Bye!".format(service_name))
break
else:
print("{0} port is not open! I'll check it soon!".format(service_name))
time.sleep(3)
By the way, this is my Dockerfile for build django-py35:
FROM python:3.5-alpine
MAINTAINER Xin Xiong "xiongxin20008#126.com"
ENV PYTHONUNBUFFERED 1
RUN set -e; \
apk add --no-cache --virtual .build-deps \
gcc \
libc-dev \
linux-headers \
mariadb-dev \
python3-dev \
postgresql-dev \
freetype-dev \
libpng-dev \
g++ \
;
RUN mkdir /djcode
WORKDIR /djcode
ENV REFRESHED_AT 2017-12-25
ADD requirements.txt /djcode/
RUN pip install --no-cache-dir -r /djcode/requirements.txt
RUN pip install uwsgi
ADD . /djcode/ # copy . to /djcode/
EXPOSE 6001
See more details from here: https://github.com/OnlyBelter/django-compose
You should use the container name instead of localhost (or 127.0.0.1) in your settings.py file. Try providing a container name to the db service in the docker-compose.yml file using container_name attribute and replace the host name in the settings.py by the value of the container_name. (Make sure that they are in the same network that docker compose creates for you.)
Build container with this:
docker run --name mysql-latest \
-p 3306:3306 -p 33060:33060 \
-e MYSQL_ROOT_HOST='%' -e MYSQL_ROOT_PASSWORD='strongpassword' \
-d mysql/mysql-server:latest
Make sure MYSQL_ROOT_HOST='%', that means root can connect from any IP.

Connect to MySQL in a docker container (Vagrant on Windows/VirtualBox)

I am trying to create a virtualised dev environment on Windows using Vagrant and Docker (as are a lot of people). The problem I have is that I cannot connect (or I dont understand how to) from MySQL Workbench running on my Windows laptop to my MySQL DB in a Docker container in Boot2Docker. This is how I visualise the connection:
MySQL Work bench -> 3306 -> Boot2Docker -> 3306 -> Docker -> MySql
However I cannot connect to the DB from MySQLWorkbench. I have tried connection to the Boot2Docker host 10.0.2.15 on 3306 and tcp over ssh using the private key of the Boot2Docker box ".vagrant\machines\dockerhost\virtualbox\id"
What am I doing wrong/what have I misunderstood.
My Vagrantfile:
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'docker'
DOCKER_HOST_NAME = "dockerhost"
DOCKER_HOST_VAGRANTFILE = "./host/Vagrantfile"
Vagrant.configure("2") do |config|
config.vm.network "forwarded_port", guest: 3306, host: 3306
config.vm.define "mysql" do |v|
v.vm.provider "docker" do |d|
d.image = "mysql"
d.env = {
:MYSQL_ROOT_PASSWORD => "root",
:MYSQL_DATABASE => "dockertest",
:MYSQL_USER => "dockertest",
:MYSQL_PASSWORD => "docker"
}
d.ports =["3306:3306"]
d.remains_running = "true"
d.vagrant_machine = "#{DOCKER_HOST_NAME}"
d.vagrant_vagrantfile = "#{DOCKER_HOST_VAGRANTFILE}"
end
end
end
My hosts/Vagrantfile (describing my Boot2docker host) is:
FORWARD_DOCKER_PORTS='true'
Vagrant.configure(2) do |config|
config.vm.provision "docker"
# The following line terminates all ssh connections. Therefore
# Vagrant will be forced to reconnect.
# That's a workaround to have the docker command in the PATH
#Clear any existing ssh connections
####NOTE: ps aux seems to give variable results depending on run -> process number can be ####first #or second causing provision to fail!!!
config.vm.provision "clear-ssh", type: "shell", inline:
"ps aux | grep 'sshd:' | awk '{print $1}' | xargs kill"
# "ps aux | grep 'sshd:' | awk '{print $2}' | xargs kill"
config.vm.define "dockerhost"
config.vm.box = "dduportal/boot2docker"
config.vm.network "forwarded_port",guest: 8080, host: 8080
config.vm.provider "virtualbox" do |vb|
vb.name = "dockerhost"
end
end
Solved. As I suspected the ports were not getting forwarded between the host machine and the docker host. The solution is to move the port forwarding config line:
config.vm.network "forwarded_port", guest: 3306, host: 3306
into the docker host Vagrant file. MySQL Workbench on the Windows host can then connect on localhost:3306.

MySQL for Linux Red Hat 5.4 - Build / Install locally as non-root - cannot start using it

I downloaded and installed My SQL from http://downloads.mysql.com/archives/mysql-5.0/mysql-5.0.91.tar.gz. The build was successfully and I installed in to a local non-root directory.
However when try to invoke mysql from command line I get the below error -
Linux:>prakash_prasad/bin/mysql-5.0.91/bin 1021> ./mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
Linux:>prakash_prasad/bin/mysql-5.0.91/bin 1022>
Googling around it states modify / create - /etc/my.cnf - but I do not have permissions to create file in /etc. There has to some other fix for the above issue. I greped which MySql files in installation directory has config /tmp/mysql.sock:
Linux:>prakash_prasad/bin/mysql-5.0.91 1018> grep -ir tmp . | grep sock
./include/mysql/mysql_version.h:#define MYSQL_UNIX_ADDR "/tmp/mysql.sock"
./bin/mysqld_safe:safe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-/tmp/mysql.sock}}
./bin/mysql_config:socket='/tmp/mysql.sock'
./bin/mysqld_multi:socket = /tmp/mysql.sock2
./bin/mysqld_multi:socket = /tmp/mysql.sock3
./bin/mysqld_multi:socket = /tmp/mysql.sock4
./bin/mysqld_multi:socket = /tmp/mysql.sock6
./share/mysql/my-small.cnf:socket = /tmp/mysql.sock
./share/mysql/my-small.cnf:socket = /tmp/mysql.sock
./share/mysql/my-medium.cnf:socket = /tmp/mysql.sock
./share/mysql/my-medium.cnf:socket = /tmp/mysql.sock
./share/mysql/my-large.cnf:socket = /tmp/mysql.sock
./share/mysql/my-large.cnf:socket = /tmp/mysql.sock
./share/mysql/my-huge.cnf:socket = /tmp/mysql.sock
./share/mysql/my-huge.cnf:socket = /tmp/mysql.sock
./share/mysql/my-innodb-heavy-4G.cnf:socket = /tmp/mysql.sock
./share/mysql/my-innodb-heavy-4G.cnf:socket = /tmp/mysql.sock
./share/man/man1/mysql-stress-test.pl.1:/tmp/mysql\&.sock\&.
./share/man/man1/mysql-test-run.pl.1:shell> \fB\&.\&./mysql \-S \&./var/tmp/master\&.sock \-h localhost \-u root\fR
./share/man/man1/mysql_config.1: \-\-socket [/tmp/mysql\&.sock]
./share/man/man1/mysqld_multi.1:shell> \fBmysql \-u root \-S /tmp/mysql\&.sock \-p\fR
./share/man/man1/mysqld_multi.1:socket = /tmp/mysql\&.sock2
./share/man/man1/mysqld_multi.1:socket = /tmp/mysql\&.sock3
./share/man/man1/mysqld_multi.1:socket = /tmp/mysql\&.sock4
./share/man/man1/mysqld_multi.1:socket = /tmp/mysql\&.sock6
./share/man/man8/mysqlmanager.8:/tmp/mysqlmanager\&.sock\&. This option has no meaning on Windows\&.
./share/man/man8/mysqlmanager.8:socket=/tmp/manager\&.sock
./share/man/man8/mysqlmanager.8:socket=/tmp/mysql\&.sock
./share/man/man8/mysqlmanager.8:socket = /tmp/mysql\&.sock5
./share/man/man8/mysqlmanager.8:| socket | /tmp/mysql\&.sock3 |
./mysql-test/suite/funcs_1/views/func_view.inc:# ./mysql-test-run.pl --socket=var/tmp/master.sock --start-dirty
./mysql-test/mysql-test-run-shell:LOCAL_SOCKET=/tmp/mysql.sock
./mysql-test/mysql-test-run-shell:MASTER_MYSOCK="$MYSQL_TMP_DIR/master.sock"
./mysql-test/mysql-test-run-shell:SLAVE_MYSOCK="$MYSQL_TMP_DIR/slave.sock"
./mysql-test/mysql-test-run-shell: $MYSQLADMIN --no-defaults -uroot --socket=$MYSQL_TMP_DIR/$ident.sock$3 --connect_timeout=5 --shutdown_timeout=70 shutdown >> $MYSQL_MANAGER_LOG 2>&1
./mysql-test/mysql-test-run-shell: $MYSQLADMIN --no-defaults -uroot --socket=$MYSQL_TMP_DIR/$ident.sock$3 --connect_timeout=1 ping >> $MYSQL_MANAGER_LOG 2>&1
./mysql-test/mysql-test-run-shell: $MYSQLADMIN --no-defaults -uroot --socket=$MYSQL_TMP_DIR/$slave_ident.sock stop-slave > /dev/null 2>&1
./mysql-test/mysql-test-run: # On QNX, /tmp/dir/master.sock and /tmp/dir//master.sock seem to be
./mysql-test/mysql-test-run: my $sockdir = $opt_tmpdir;
./mysql-test/mysql-test-run: $master->[0]->{'path_sock'}= $opt_socket ? $opt_socket : "/tmp/mysql.sock";
./mysql-test/mtr: # On QNX, /tmp/dir/master.sock and /tmp/dir//master.sock seem to be
./mysql-test/mtr: my $sockdir = $opt_tmpdir;
./mysql-test/mtr: $master->[0]->{'path_sock'}= $opt_socket ? $opt_socket : "/tmp/mysql.sock";
./mysql-test/mysql-test-run.pl: # On QNX, /tmp/dir/master.sock and /tmp/dir//master.sock seem to be
./mysql-test/mysql-test-run.pl: my $sockdir = $opt_tmpdir;
./mysql-test/mysql-test-run.pl: $master->[0]->{'path_sock'}= $opt_socket ? $opt_socket : "/tmp/mysql.sock";
./mysql-test/mysql-stress-test.pl:$opt_server_socket= $opt_server_socket ? $opt_server_socket : "/tmp/mysql.sock";
Linux:>prakash_prasad/bin/mysql-5.0.91 1019>
Now I not sure what changes I have to make to be able to use it.
Thanks in advance
Create your my.cnf wherever you want and start the server with
/path/to/mysqld --defaults-file=/path/to/my.cnf
try the --defaults-extra-file=path option if you can't change the /etc/my.cnf file.
Or, if you only want to change the socket, use: --socket=/tmp/mysql.sock