takaya030の備忘録

PHP、Laravel、Docker などの話がメインです

Docker で CentOS7 + Apache2.4 + PHP7 環境のイメージを作る

CentOS7 で動作する Apache + PHP の環境を作成したときの手順メモ

Docker 環境

Windows10 Home Edition
VirtualBox 5.1.6
docker 1.10.3
docker-machine 0.6.0

各種設定ファイル

Dockerfile

#
# Apache + PHP
#
# 2017-01-15
#   CentOS 7.3 + epel,remi
#   Apache 2.4.6
#   PHP 7.0.14

FROM centos:7
MAINTAINER takaya030

# update yum
RUN yum update -y && \
    yum clean all

# epel,remi
RUN yum install -y epel-release && \
	yum install -y http://rpms.famillecollet.com/enterprise/remi-release-7.rpm && \
    yum clean all && \
	sed -i -e "s/enabled *= *1/enabled=0/g" /etc/yum.repos.d/epel.repo && \
	sed -i -e "s/enabled *= *1/enabled=0/g" /etc/yum.repos.d/remi.repo

# httpd, sshd, scp, openssl, sudo, which
RUN yum install -y httpd httpd-tools openssh-server openssh-clients openssl sudo which && \
    yum clean all

# libmcrypt, supervisor
RUN yum install --enablerepo=epel -y libmcrypt supervisor && \
    yum clean all

# gd-last (for php-gd)
RUN yum install --enablerepo=remi -y gd-last && \
    yum clean all

# php-pecl-memcached
RUN yum install --enablerepo=remi,remi-php70 -y php-pecl-memcached && \
    yum clean all

# php
RUN yum install --enablerepo=remi-php70 -y php php-devel php-gd php-mbstring php-mcrypt php-mysqlnd php-pear php-xml php-opcache && \
    yum clean all && \
	sed -i -e "s/;date.timezone *=.*$/date.timezone = Asia\/Tokyo/" /etc/php.ini

# composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# phpunit
RUN curl -L https://phar.phpunit.de/phpunit.phar > /usr/local/bin/phpunit && \
	chmod +x /usr/local/bin/phpunit

# initialize for ssh
RUN sed -i '/pam_loginuid\.so/s/required/optional/' /etc/pam.d/sshd && \
	ssh-keygen -A

# create login user
RUN useradd -d /home/laravel -m -s /bin/bash laravel && \
	echo laravel:****laravel | chpasswd && \
	echo 'laravel ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# timezone
RUN cp -p /usr/share/zoneinfo/Japan /etc/localtime

ENV WEBAPP_ROOT /webapp

ADD ./httpd.conf /etc/httpd/conf/httpd.conf
ADD ./index.html /webapp/public/index.html
ADD ./phpinfo.php /webapp/public/phpinfo.php
ADD ./supervisord.conf /etc/supervisord.conf

EXPOSE 22 80

CMD ["/usr/bin/supervisord"]

index.html

<html>
	<body>
		<h1>It works!</h1>
		<p><a href="./phpinfo.php">phpinfo</a></p>
	</body>
</html>

phpinfo.php

<?php
    phpinfo();

supervisor.conf

長いので diff のみ

--- supervisord.conf.orig	Sun Jan 15 18:31:07 2017
+++ supervisord.conf	Sun Jan 15 19:08:05 2017
@@ -18,7 +18,7 @@
 logfile_backups=10          ; (num of main logfile rotation backups;default 10)
 loglevel=info               ; (log level;default info; others: debug,warn,trace)
 pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
-nodaemon=false              ; (start in foreground if true;default false)
+nodaemon=true              ; (start in foreground if true;default false)
 minfds=1024                 ; (min. avail startup file descriptors;default 1024)
 minprocs=200                ; (min. avail process descriptors;default 200)
 ;umask=022                  ; (process file creation umask;default 022)
@@ -127,3 +127,9 @@
 
 [include]
 files = supervisord.d/*.ini
+
+[program:sshd]
+command=/usr/sbin/sshd -D
+
+[program:httpd]
+command=/usr/sbin/httpd -DFOREGROUND

httpd.conf

長いので diff のみ

--- httpd.conf.orig	Sun Jan 15 18:31:49 2017
+++ httpd.conf	Sun Jan 15 19:38:42 2017
@@ -93,6 +93,7 @@
 # If your host doesn't have a registered DNS name, enter its IP address here.
 #
 #ServerName www.example.com:80
+ServerName webapp:80
 
 #
 # Deny access to the entirety of your server's filesystem. You must
@@ -116,7 +117,8 @@
 # documents. By default, all requests are taken from this directory, but
 # symbolic links and aliases may be used to point to other locations.
 #
-DocumentRoot "/var/www/html"
+#DocumentRoot "/var/www/html"
+DocumentRoot "${WEBAPP_ROOT}/public"
 
 #
 # Relax access to content within /var/www.
@@ -128,7 +130,8 @@
 </Directory>
 
 # Further relax access to the default document root:
-<Directory "/var/www/html">
+#<Directory "/var/www/html">
+<Directory "${WEBAPP_ROOT}/public">
     #
     # Possible values for the Options directive are "None", "All",
     # or any combination of:
@@ -148,7 +151,7 @@
     # It can be "All", "None", or any combination of the keywords:
     #   Options FileInfo AuthConfig Limit
     #
-    AllowOverride None
+    AllowOverride All
 
     #
     # Controls who can get stuff from this server.
@@ -161,7 +164,7 @@
 # is requested.
 #
 <IfModule dir_module>
-    DirectoryIndex index.html
+    DirectoryIndex index.php index.html
 </IfModule>
 
 #

httpd.conf と supervisor.conf の完全版はこちらに置いてあります
centos7_httpd.conf GitHub

イメージのビルド

$ docker build -t takaya030/webapp

イメージの確認

$ docker images
REPOSITORY                         TAG                 IMAGE ID            CREATED             SIZE
takaya030/webapp                   latest              46e548051792        3 hours ago         528 MB
centos                             7                   67591570dd29        4 weeks ago         191.8 MB

動作確認

$ docker run -d -p 80:80 -p 2022:22 --name webapp takaya030/webapp

WEBブラウザで "http://192.168.99.100" にアクセスして下の画像のように表示されれば動作しています。
f:id:takaya030:20150902010402p:plain

Windows の git bash (msysgit) 環境の Docker コマンドを手動アップグレード

msysgit にインストールされた docker コマンドを手動アップグレードしたときの手順メモ

動作環境

Windows10 Home Edition
VirtualBox 5.1.6
docker 1.10.3
docker-machine 0.6.0

docker コマンドの最新バージョン

2017/1/1 現在の Latest Release バージョン

docker 1.12.5

dokcer コマンドのダウンロード

以下のリンクからダウンロード。解凍した docker.exe を古い exe と入れ替える
Windows 64bits zip: https://get.docker.com/builds/Windows/x86_64/docker-1.12.5.zip

動作確認

$ docker -v
Docker version 1.12.5, build 7392c3b

$ docker images
Error response from daemon: client is newer than server (client API version: 1.24, server API version: 1.22)

Client API バージョンが合っていないためエラーが出ている
docker-machine upgrade で Docker ホスト(CoreOS)のアップグレードをすることで解消される

$ docker-machine upgrade default
Waiting for SSH to be available...
Detecting the provisioner...
Upgrading docker...
Stopping machine to do the upgrade...
Upgrading machine "default"...
Default Boot2Docker ISO is out-of-date, downloading the latest release...
Latest release for github.com/boot2docker/boot2docker is v1.12.5
Downloading C:\Users\takaya030\.docker\machine\cache\boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v1.12.5/boot2docker.iso...
0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100%
Copying C:\Users\takaya030\.docker\machine\cache\boot2docker.iso to C:\Users\takaya030\.docker\machine\machines\default\boot2docker.iso...
Starting machine back up...
(default) Check network to re-create if needed...
(default) Waiting for an IP...
Restarting docker...

$ docker images
REPOSITORY                         TAG                 IMAGE ID            CREATED             SIZE
mysql                              5.6                 72010d7c69f5        16 months ago       283.6 MB
centos                             6                   93f242d546bd        18 months ago       203.1 MB
busybox                            latest              63e6ca37d7f4        20 months ago       2.433 MB

Windows + VirtualBox + Docker で動作しているコンテナから XAMPP の MySQL へアクセス

前回 Docker コンテナからホスト OS (Windows)へのアクセス可能なことを確認しましたが、今回はその応用でコンテナから XAMPP の MySQL に接続してみます

動作環境

以下の環境で検証しました
VirtualBoxDocker はインストール済みの前提で話を進めます

Windows10 Home Edition
VirtualBox 5.1.6
docker 1.10.3
docker-machine 0.6.0

デフォルトルートの確認

コンテナからホストOS (Windows) へのアクセスはデフォルトルートを通じて行うことが可能です
デフォルトルートは CoreOS 上で "ip r" と入力することで確認可能です

$ ip r
default via 10.0.2.2 dev eth0  metric 1
10.0.2.0/24 dev eth0  proto kernel  scope link  src 10.0.2.15
127.0.0.1 dev lo  scope link
172.17.0.0/16 dev docker0  proto kernel  scope link  src 172.17.0.1
172.18.0.0/16 dev br-5b890ae3c1a7  proto kernel  scope link  src 172.18.0.1
172.19.0.0/16 dev br-0fef2cb04591  proto kernel  scope link  src 172.19.0.1
192.168.99.0/24 dev eth1  proto kernel  scope link  src 192.168.99.100

自分の環境ではデフォルトルートのアドレスは 10.0.2.2 でした

XAMPP の MySQL の起動

xampp-controlMySQL を起動します
f:id:takaya030:20161029191234p:plain

コンテナから XAMPP の MySQL に接続

$ mysql -u root -h 10.0.2.2
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.6.21 MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

以上、コンテナから XAMPP の MySQL にアクセス可能なことが確認できました

Windows + VirtualBox + Docker で動作しているコンテナからホスト OS へのアクセス

Docker コンテナからホスト OS (CoreOS,Windows)へのアクセス方法について

動作環境

以下の環境で検証しました
VirtualBoxDocker はインストール済みの前提で話を進めます

Windows10 Home Edition
VirtualBox 5.1.6
docker 1.10.3
docker-machine 0.6.0

ブリッジインターフェースの確認

Docker のネットワークを管理している仮想ブリッジ "docker0" を確認します。
CoreOS 上で "ip a" と入力することで確認可能です。

$ ip a

7: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:d4:14:51:45 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 scope global docker0
       valid_lft forever preferred_lft forever

自分の環境では docker0 のアドレスは 172.17.0.1 でした

コンテナから CoreOS へのアクセス

コンテナから CoreOS へのアクセスは仮想ブリッジ "docker0" を通じて行うことが可能です

$ ping 172.17.0.1
PING 172.17.0.1 (172.17.0.1) 56(84) bytes of data.
64 bytes from 172.17.0.1: icmp_seq=1 ttl=64 time=0.784 ms
64 bytes from 172.17.0.1: icmp_seq=2 ttl=64 time=0.098 ms
64 bytes from 172.17.0.1: icmp_seq=3 ttl=64 time=0.086 ms
64 bytes from 172.17.0.1: icmp_seq=4 ttl=64 time=0.085 ms

コンテナから Windows へのアクセス

コンテナから Windows へのアクセスはデフォルトルートを通じて行うことが可能です
デフォルトルートは CoreOS 上で "ip r" と入力することで確認可能です

$ ip r
default via 10.0.2.2 dev eth0  metric 1
10.0.2.0/24 dev eth0  proto kernel  scope link  src 10.0.2.15
127.0.0.1 dev lo  scope link
172.17.0.0/16 dev docker0  proto kernel  scope link  src 172.17.0.1
172.18.0.0/16 dev br-5b890ae3c1a7  proto kernel  scope link  src 172.18.0.1
172.19.0.0/16 dev br-0fef2cb04591  proto kernel  scope link  src 172.19.0.1
192.168.99.0/24 dev eth1  proto kernel  scope link  src 192.168.99.100

自分の環境ではデフォルトルートのアドレスは 10.0.2.2 でした

$ ping 10.0.2.2
PING 10.0.2.2 (10.0.2.2) 56(84) bytes of data.
64 bytes from 10.0.2.2: icmp_seq=1 ttl=62 time=0.226 ms
64 bytes from 10.0.2.2: icmp_seq=2 ttl=62 time=0.466 ms
64 bytes from 10.0.2.2: icmp_seq=3 ttl=62 time=0.537 ms
64 bytes from 10.0.2.2: icmp_seq=4 ttl=62 time=0.435 ms

以上、コンテナから CoreOS、Windows 双方にアクセス可能なことが確認できました

Docker 版 Rails5 で Hello world

Docker で構築した Ruby on Rails5 の環境で "Hello world!" を表示してみる

コントローラ作成

Docker ホストOS 上で下記コマンドで作成

$ docker-compose run --rm web rails generate controller hello
      create  app/controllers/hello_controller.rb
      invoke  erb
      create    app/views/hello
      invoke  test_unit
      create    test/controllers/hello_controller_test.rb
      invoke  helper
      create    app/helpers/hello_helper.rb
      invoke    test_unit
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/hello.coffee
      invoke    scss
      create      app/assets/stylesheets/hello.scss

index のアクション作成

app/controllers/hello_controller.rb

class HelloController < ApplicationController
	def index
		render :text => "Hello, world!"
	end
end

ルーティング

config/routes.rb

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  resources :hello do
	  root 'hello#index'
  end
end

動作確認

web ブラウザで http://192.168.99.100:3000/hello を開いて "Hello, world!" と表示されれば成功です

Docker で Rails5 + MySQL の開発環境を構築する

前回 Docker で Ruby on Rails5 のサーバーを単体で起動させましたが、今回は MySQL 連携させてみました。

設定ファイルおよび操作手順について

こちらのサイトに記載されている手順とほぼ同じです。
qiita.com


以下、内容を変更した設定ファイルです。

Dockerfile

#
# ruby 2.3 + rails 5.0.0.1
#
# 2016-10-10
#

FROM ruby:2.3
MAINTAINER takaya030

RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp

Gemfile

source "https://rubygems.org"
gem 'rails', '5.0.0.1'

docker-compose.yml

version: '2'
services:
  db:
    image: mysql:5.6
    container_name: rr5_db
    environment:
      MYSQL_ROOT_PASSWORD: root
  web:
    build: .
    image: rr5_web
    container_name: rr5_web
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/myapp
    ports:
      - "3000:3000"
    depends_on:
      - db

Docker で Ruby on Rails5 の開発環境を構築する

Docker で Ruby on Rails5 の開発環境のベースイメージを作成したときの手順メモ

設定ファイルおよび操作手順について

こちらのサイトに記載されている手順で rails5 もセットアップできました。
qiita.com


以下、内容を変更した設定ファイルです。

Dockerfile

#
# ruby 2.3 + rails 5.0.0.1
#
# 2016-10-05
#

FROM ruby:2.3
MAINTAINER takaya030

ENV APP_ROOT /usr/src/myapp

WORKDIR $APP_ROOT

RUN apt-get update && \
    apt-get install -y nodejs \
                       mysql-client \
                       postgresql-client \
                       sqlite3 \
                       --no-install-recommends && \
    rm -rf /var/lib/apt/lists/*

COPY Gemfile $APP_ROOT
COPY Gemfile.lock $APP_ROOT

RUN \
  echo 'gem: --no-document' >> ~/.gemrc && \
  cp ~/.gemrc /etc/gemrc && \
  chmod uog+r /etc/gemrc && \
  bundle config --global build.nokogiri --use-system-libraries && \
  bundle config --global jobs 4 && \
  bundle install && \
  rm -rf ~/.gem

# bundle install でカレントディレクトリに rails5 をインストールした後、
# 以下をコメントアウトして再度 docker build を実行する

#COPY . $APP_ROOT
#
#EXPOSE  3000
#CMD ["rails", "server", "-b", "0.0.0.0"]

Gemfile

source "https://rubygems.org"
gem 'rails', '5.0.0.1'

docker-compose.yml

version: '2'
services:
  app:
    build: .
    image: developer_name/project_name
    container_name: project_name_app
    environment:
      RAILS_ENV: development
    command: bundle exec rails s -p 3000 -b '0.0.0.0'
    volumes:
      - .:/usr/src/myapp
    ports:
      - "3000:3000"