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 *

関連記事

In emacs on iTerm2, resolve you can’t enter symbol key binding such as C-; C-: C-> C-< C-. C-,

Abstract Hello eveyone it’s me candle. This time I will show you how to solve the problem that you can’t use symbol keybind on your iTerm2 emacs. Basically, emacs on iTerm2 can’t use key binding of control + symbol. The detail thing is written in this article. (japanese) http://memo.sugyan.com/entry/20120224/1330051378 Acouding to the article Apparently it seems that the range of ASCII that ctrl key can control is decided. This post referred to the below linked article. I tried how to setup symbol key binding a few years ago and I was frustrated. But I solved it by that. it was …

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 …

Hide Google Chrome 70 “For quick access, place your bookmarks …” bar

Abstract Hello everyone it’s me candle. I usually use Safari. Sometimes using Google Chrome, I forget how to turn off the bookmark bar. First I will write two important things. Google Chrome 70 turn off the book mark bar by default. In the top page of Google Chrome 70, the bookmark bar is definitely displayed Condition You use Google Chrome Turn off it Open Google Chrome, choose “Settings” from the menu icon in the top right. If you turn off “Show bookmarks bar” in the second “Design” area from the top, bookmark bar disappears. It’s over Conclusion Simple is best.

Build flycheck + eslint environment supporting to react + es6 in Emacs.

Abstract Hello everyone it’s me candle. In this time let’s build emacs + eslint. There are many other syntax check packages such as jsHint, jsxHint, etc which check the coding rule of javascript. According to web info, these packages seem to be unable to adapt well with the latest javascript writing format such as React and es6. Nowadays eslint became to be mainstream. It has become used not only in emacs but also everywhere. I’m also emacs user, try it! I’m not a node JS and Elisp professional, it may contains useless writing or wrong writing. Please go easy on …

Build PlantUML environment on Mac using brew

Abstract Hello everybody it’s me candle. In this article, I would like to build a plantUML environment which can make UML easily on Mac. I have been used starUML for making UML. plantUML seems to be much more useful than that. Precondition You already use brew. Check java version I think that java is already installed in your mac pc. PlantUML can be run with mac default java. So you launch terminal app and check the java version with the below command. java -version Probably it can be work in java version around 1.8.x . Install graphviz graphviz is a …


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.