joppot

コピペで絶対動く。説明を妥協しない

ソフトウェア

Connect to host mysql from docker container of “docker for Mac”

投稿日:


Abstract

Hello everyone it’s me candle.
In this post I will show you how to connect to the host mysql from the docker container of mac.

For example, you may connect to mysql when running rails, wordpress etc on docker.
You may prepare docker of mysql, but it can’t hold data, it is troublesome such as startup time.
Then I think that it is very useful if docker can access to the host mysql.

Precondition

You use docker for mac


Create mysql database for testing

As a my explain method, this post will explain with a tutorial format.
If you want to know about a important part, skip this chapter and next chapter please.

First let’s create database.

Launch the terminal app and create the file.

touch ~/pokemondb.sql

Write this to the pokemondb.sql

CREATE DATABASE `pokemondb` DEFAULT CHARACTER SET utf8;

USE `pokemondb`;

DROP TABLE IF EXISTS `pokemon`;
CREATE TABLE `pokemon` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `pokemon` VALUES (1,'Pikachu','Electric'),(2,'Garchomp','Dragon Ground');

Load this file.

mysql -u root -p < ~/pokemondb.sql

The database is ready to start.

Create a docker container for testing

In this article, we create nginx and php-fpm container and access host mysql from php.

I almost copied structure of docker from the below site.

http://takaya030.hatenablog.com/entry/20160504/1462330190

The structure is like this.

mysqltest/
├── docker-compose.yml
├── nginx
│ ├── Dockerfile
│ └── server.conf
└── php7
    ├── Dockerfile
    └── index.php

Execute these commands in a any folder.

mkdir mysqltest && cd mysqltest
touch docker-compose.yml && mkdir nginx && mkdir php7
touch nginx/Dockerfile nginx/server.conf
touch php7/Dockerfile php7/index.php

Write the below code in the each files.

docker-compose.yml

nginx:
  build: ./nginx
  ports:
    - "80:80"
  links:
    - php7

php7:
  build: ./php7


nginx/Dockerfile

FROM nginx:latest
MAINTAINER candle

ADD server.conf /etc/nginx/conf.d/server.conf


nginx/server.conf

server {
  listen 80 default;
  server_name _;
  root /var/www/html;
  index index.php index.html index.htm;
  charset utf-8;

  access_log off;
  error_log off;

  location / {
    try_files $uri $uri/ /index.php$is_args$args;
  }
  location ~ .php$ {
    fastcgi_pass mysqltest_php7_1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include       fastcgi_params;
  }
}


php7/Dockerfile

FROM php:7-fpm
MAINTAINER candle

RUN /usr/local/bin/docker-php-ext-install mysqli
COPY index.php /var/www/html/


php7/index.php

<?php

$mysqli = new mysqli('10.200.10.1', 'root', '', 'pokemondb');
if ($mysqli->connect_error) {
  echo $mysqli->connect_error;
  exit();
} else {
  $mysqli->set_charset("utf8");
}


$sql = "SELECT * FROM pokemon";
if ($result = $mysqli->query($sql)) {
  while ($row = $result->fetch_assoc()) {
    echo $row["name"] ."&nbsp;". $row["type"] . "<br>";
  }
  $result->close();
}

$mysqli->close();
?>

The necessary files were prepared.

Add to write.
I will supplement a little.

index.php is important.
It accesses to the host mysql from the docker container.

$mysqli = new mysqli(‘10.200.10.1’, ‘root’, ”, ‘pokemondb’);

is

$mysqli = new mysqli(‘host_name’, ‘user_name’, ‘password’, ‘database_name’);


Allocate new local IP address

As you can see from the above index.php code, php is trying to access 10.200.10.1.
However, the lo0 IP address allocated to the host Mac is 127.0.0.1.

Ther problem is that docker can access to the hsot mysql 127.0.0.1
I do not know detail, but it seems that something like that.

Then we will add new lo0 IP address 10.200.10.1 to the Mac.
This 10.200.10.1 number was referred to the official docs of docker.

https://docs.docker.com/docker-for-mac/networking/

Launch the terminal app of mac and execte this.
Allocate 10.200.10.1 to lo0

sudo ifconfig lo0 alias 10.200.10.1/24

After that check it with the below command.

ifconfig

You have to run the command which allocates IP address to the lo0 in every time when you start up Mac PC.
The method of automatically allocating IP is introduced in this article, so please refer to it.

https://joppot.info/en/2017/09/14/4072

It’s ready.


Lauch docker

Execute this in the folder containing docker-compose.yml exsist

docker-compose up -d

You will check the image when it is over.

docker images

Confirm the running container.

docker ps

Nginx is running in 80 port.
Access URL with browser.

http://127.0.0.1

php has accessed mysql and got data.


Conclusion

It was difficult around the network, and tried and error was made in various ways.

スポンサードリンク

If you think this article is good, share it please

-ソフトウェア
-, ,

執筆者:


comment

Your email address will not be published. Required fields are marked *

関連記事

How to use f.lux, blue light cut software

Abstract Hello everyone. In this time I will explain how to use f.lux. f.flux can reduce the amount of blue light as much as possible. f.lux can adjust the blue light cut rate with the seek bar. Please try using it. Condition You use Mac or Windows I will explain it in Mac PC. Download f.lux Go to the blew site. http://justgetflux.com/ Click the center “Download f.lux” button. Once you have downloaded the zip file, let’s double-click it and extract it. Since The executable file is expanded in the download folder, move it to the Application folder. It’s over. Use …

Atom imports React component using import-js 2.2.0

Abstract Hello everybody it’s me candle. In this time we will import the component path into the file using import-js and Atom automatically. React recommends to write one component in one file, when development becomes to be big, the number of component increase. If you use 10 components with one Container, you need to write 10 import statements. import-js helps us from such troublesome work. Precondition Already exist React web environment I recommend you use the react project created by create-react-app command which I wrote the before article. Atom was installed in your computer.

Using vc to manage git on emacs25

Abstract Hello everyone it’s me candle. In this article we would like to use vc(version controll) which is included by deault in emacs. It seems that vc supports to both subversion and git, not git-specific functions. If you want to use git with emacs in earnest, I recommend magit. On the other hand, since vc is installed in by default, it is good for user who want to use it easily. Precondition You use emacs You have a basic git skill. vc-git configuration of emacs Although vc supports to git, ‘git add’ and ‘git reset HEAD’ do not exist. I …

Write haml with Atom

English 日本語 Abstract Hello everybody, it’s candle. In this time we will write haml with Atom. I’m coding with emacs for all time. but sotimes I use atom. When I open a haml file, there is no coloring and syntax, I try to add plugin. Premise You have Atom editor.

How to invert photoshop brush

English 日本語 Abstract Hello everyone. It’s candle. In this time, I’ll show you how to invert brush effect. Precondition Nothing


I work in the venture company as a CTO. I start to write program in University, first I learned java, C++ and PHP. In the company, I'm developing web services by Rails. I do like to automation.