5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Docker for WindowsでLAMP環境(Laravel動作環境)を構築する

Last updated at Posted at 2020-05-07

※2018/09/25 時点の内容をベースにまとめたため、古い情報が含まれています。
※各ソースは https://github.com/dai-andy1976/docker_laravel から参照できます。

#インストール
##Docker for Windowsをインストールする際の前提条件

  • Windows10にDocker for Windowsをインストールします。
  • Windowsの仮想化システムHyper-Vが必須となります。このため、Hyper-Vが使用できない**Windows10 Homeではインストールすることができません。**
  • Windows10 Homeの場合は、Windows10 Proにアップグレードする必要があります(アップグレードに関しては、今回取り上げません)。

##Windows10のエディションの確認方法

  • エクスプローラーを起動し、「PC」を右クリックします。サブウインドウから「プロパティ」を選択します。
    全画面キャプチャ 20200425 173434.jpg

  • エディションが確認できます。
    全画面キャプチャ 20200426 141504.jpg

##Hyper-Vの有効化

  • Windowsのスタートボタンを右クリックします。「アプリと機能」を選択します。
    全画面キャプチャ 20200426 141507.jpg

  • 「プログラムと機能」をクリックします。
    全画面キャプチャ 20200426 141510.jpg

  • 「Windowsの機能の有効化または無効化」をクリックします。
    全画面キャプチャ 20200426 141512.jpg

  • 「Hyper-V」にチェックを入れます。
    全画面キャプチャ 20200426 141515.jpg

##Docker for Windowsのインストール

  • ダウンロードサイト(https://store.docker.com/editions/community/docker-ce-desktop-windows) へアクセスします。

    「Get Docker for Windows(Stable)」ボタンを押下して、安定版をダウンロードします。

    ※ダウンロードする際に、アカウントの登録が必要となります。

    全画面キャプチャ 20200426 141519.jpg

  • ダウンロードしたファイルをクリックします。
    全画面キャプチャ 20200426 141522.jpg

  • インストーラーが起動します。デフォルトの設定のまま「OK」ボタンを押下して進めてください。
    全画面キャプチャ 20200426 141524.jpg

  • パッケージがインストールされます。
    全画面キャプチャ 20200426 141526.jpg

  • インストールが終わると「installation succeeded」と表示されます。「Close」ボタンを押下して、インストールを終了してください。
    全画面キャプチャ 20200426 141529.jpg

  • Docker for Windowsのインストールが終わったら、一旦 PCを再起動してください。

  • PC起動後、タスクバーに「Docker for Windows」のアイコンが追加されている事を確認します。
    全画面キャプチャ 20200426 141531.jpg

  • アイコンを右クリックし、「Settings」を選択します。
    全画面キャプチャ 20200426 141536.jpg

  • 設定メニューが表示されます。
    全画面キャプチャ 20200426 141539.jpg

  • 「Shared Drivers」を選択します。PCのCドライブをディスク領域としてDockerで使用するので、チェックを入れいます。「Apply」ボタンを押下します。全画面キャプチャ 20200426 141541.jpg

  • 「Network」を選択します。DNS Serverを「Fixed 8.8.8.8」で設定します。「Apply」ボタンを押下します。
    全画面キャプチャ 20200426 141546.jpg

  • アイコンを右クリックし、「Sign in / Create Docker ID」を選択します。
    全画面キャプチャ 20200426 141552.jpg

  • Docker ID と Password を入力し、「Sign in」ボタンを押下して、Docker Cloudへログインします。
    Docker Cloudのアカウントを取得していない場合は、https://cloud.docker.com でアカウントを取得してください。
    全画面キャプチャ 20200426 141555.jpg

##Docker for Windowsの起動確認

  • Windowsのスタートボタンを右クリックします。「Windows PowerShell(管理者)」を選択します。
    全画面キャプチャ 20200426 141603.jpg

  • Windows PowerShell(管理者)が起動します。「docker version」を入力します。

    ※ClientとServerの情報が表示されることを確認してください。

PS C:\WINDOWS\system32> docker version
Client:
 Version:           18.06.1-ce
 API version:       1.38
 Go version:        go1.10.3
 Git commit:        e68fc7a
 Built:             Tue Aug 21 17:21:34 2018
 OS/Arch:           windows/amd64
 Experimental:      false

Server:
 Engine:
  Version:          18.06.1-ce
  API version:      1.38 (minimum version 1.12)
  Go version:       go1.10.3
  Git commit:       e68fc7a
  Built:            Tue Aug 21 17:29:02 2018
  OS/Arch:          linux/amd64
  Experimental:     false

#DB構築
※ここでは「Gauth」というプロジェクトを例にしています。

##ディレクトリ作成

  • Windows PowerShell(管理者)を起動します。CドライブのルートディレクトリにあるDockerディレクトリ直下に、Gauthディレクトリを作成します。

    ※CドライブのルートディレクトリにあるDockerディレクトリが無い場合は、Dockerディレクトリを作成してください。
PS C:\> cd C:\Docker\
PS C:\Docker> mkdir Gauth


    ディレクトリ: C:\Docker


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     10:20                Gauth
  • プロジェクト用ディレクトリ内に、MySQL用ディレクトリ(データディレクトリ含む)を作成します。
PS C:\Docker> cd .\Gauth\
PS C:\Docker\Gauth> mkdir mysql


    ディレクトリ: C:\Docker\Gauth


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     10:22                mysql


PS C:\Docker\Gauth> cd .\mysql\
PS C:\Docker\Gauth\mysql> mkdir mysql_data


    ディレクトリ: C:\Docker\Gauth\mysql


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     10:22                mysql_data

##Dockerfileとmy.cnfの作成

  • MySQL用のイメージ作成定義ファイルDockerfileと、MySQLの定義ファイルmy.cnfファイルを作成します。mysqlディレクトリ直下に、Dockerfileとmy.cnfを作成します。
PS C:\Docker\Gauth\mysql> ls


    ディレクトリ: C:\Docker\Gauth\mysql


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     10:22                mysql_data
-a----       2018/09/25     10:30            128 Dockerfile
-a----       2018/09/25     10:31            116 my.cnf
Dockerfile
FROM mysql:5.7
EXPOSE 3306

ADD ./my.cnf /etc/mysql/conf.d/my.cnf
RUN chmod 644 /etc/mysql/conf.d/my.cnf

CMD ["mysqld"]
my.cnf
[mysqld]
character-set-server=utf8

[mysql]
default-character-set=utf8

[client]
default-character-set=utf8

##docker-compose.ymlの作成

  • Dockerの管理ファイルdocker-compose.ymlを作成します。
PS C:\Docker\Gauth> ls


    ディレクトリ: C:\Docker\Gauth


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     10:30                mysql
-a----       2018/09/25     10:35            502 docker-compose.yml
docker-compose.yml
version: "3"
services:
  db:
    build: ./mysql
    ports:
      - 3307:3306
    environment:
      MYSQL_ROOT_PASSWORD: root
      TZ: Asia/Tokyo
    volumes:
      - ./mysql/mysql_data:/var/lib/mysql
    container_name: "mysql5.7"
  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    ports:
      - 8080:80
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    container_name: "phpmyamin-la"

##Dockerイメージ作成

  • MySQLのDockerイメージを作成します。
PS C:\Docker\Gauth> docker-compose build
Building db
Step 1/5 : FROM mysql:5.7
 ---> 563a026a1511
Step 2/5 : EXPOSE 3306
 ---> Using cache
 ---> 14c5b3522dcb
Step 3/5 : ADD ./my.cnf /etc/mysql/conf.d/my.cnf
 ---> bb0ed17eb1f2
Step 4/5 : RUN chmod 644 /etc/mysql/conf.d/my.cnf
 ---> Running in b905b1a1c0d3
Removing intermediate container b905b1a1c0d3
 ---> 62d2c1e30c11
Step 5/5 : CMD ["mysqld"]
 ---> Running in ba5835ff49bd
Removing intermediate container ba5835ff49bd
 ---> b13e71bd1d84
Successfully built b13e71bd1d84
Successfully tagged gauth_db:latest
phpmyadmin uses an image, skipping
  • 作成したイメージを確認します。
PS C:\Docker\Gauth> docker images
REPOSITORY                 TAG                 IMAGE ID            CREATED              SIZE
gauth_db                   latest              b13e71bd1d84        About a minute ago   372MB
mysql                      5.7                 563a026a1511        2 weeks ago          372MB
phpmyadmin/phpmyadmin      latest              126b8717cebb        4 weeks ago          166MB
centos                     7.4.1708            d3949e34634c        7 weeks ago          197MB
docker4w/nsenter-dockerd   latest              cae870735e91        11 months ago        187kB

##Dockerコンテナ作成

  • MySQLとPHP MyAdminのDockerコンテナを起動します。
PS C:\Docker\Gauth> docker-compose up -d
Creating network "gauth_default" with the default driver
Creating mysql5.7 ... done
Creating phpmyamin-la ... done
  • 起動したコンテナを確認します。
PS C:\Docker\Gauth> docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED              STATUS              PORTS                               NAMES
4bf256c36729        phpmyadmin/phpmyadmin:latest   "/run.sh supervisord…"   About a minute ago   Up About a minute   9000/tcp, 0.0.0.0:8080->80/tcp      phpmyamin-la
9295ffc1afc9        gauth_db                       "docker-entrypoint.s…"   About a minute ago   Up About a minute   33060/tcp, 0.0.0.0:3307->3306/tcp   mysql5.7

##PHP MyAdminからDBへのアクセス

  • ブラウザで http://localhost:8080/ へアクセスします。

    PHP MyAdmin が表示されることを確認します。
    全画面キャプチャ 20200426 224144.jpg
    ※表示されない場合は、docker ps でコンテナが正常に起動しているか確認してください。

  • PHP MyAdminへログインします。
    サーバ:db、ユーザ名:root、パスワード:root を入力し、実行ボタンを押下してください。
    全画面キャプチャ 20200426 224149.jpg

  • ログイン後のPHP MyAdminの画面が表示されます。
    全画面キャプチャ 20200426 224153.jpg

##データベースの追加

  • データベースを追加します。

    「NEW」を選択してください。
    全画面キャプチャ 20200426 224157.jpg

  • データベースを新規に作成します。

    データベース名と文字コードを入力し、「作成」ボタンを押下してください。
    全画面キャプチャ 20200426 224200.jpg

  • データベースが作成されました。
    全画面キャプチャ 20200426 224203.jpg

#WEB構築
##Dockerfileとapache.confの作成

  • プロジェクト用ディレクトリ内に、PHP用ディレクトリを作成します。
PS C:\Docker\Gauth> mkdir apache-php


    ディレクトリ: C:\Docker\Gauth


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     11:47                apache-php
  • PHP用のイメージ作成定義ファイルDockerfileと、apacheの設定ファイルを作成します。

    apache-phpディレクトリ直下に、Dockerfileとapache.confを作成します。
PS C:\Docker\Gauth> cd .\apache-php\
PS C:\Docker\Gauth\apache-php> ls


    ディレクトリ: C:\Docker\Gauth\apache-php


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       2018/09/25     11:54          11826 apache.conf
-a----       2018/09/25     11:50           1017 Dockerfile
Dockerfile
FROM centos:7.4.1708

RUN yum -y update

# 言語を日本語に設定
RUN localedef -i ja_JP -f UTF-8 ja_JP.UTF-8
RUN echo 'LANG="ja_JP.UTF-8"' >  /etc/locale.conf
ENV LANG ja_JP.UTF-8

# 日付を日本語に設定
RUN echo 'ZONE="Asia/Tokyo"' > /etc/sysconfig/clock
RUN rm -f /etc/localtime
RUN ln -fs /usr/share/zoneinfo/Asia/Tokyo /etc/localtime

# 外部リポジトリ(EPEL, Remi)を追加
RUN yum -y install epel-release
RUN yum -y install http://rpms.remirepo.net/enterprise/remi-release-7.rpm

# apache その他 phpパッケージを導入
RUN yum -y install httpd
RUN yum -y install --enablerepo=remi,remi-php71 php php-cli php-common php-devel php-fpm php-gd php-mbstring php-mysqlnd php-pdo php-pear php-pecl-apcu php-soap php-xml php-xmlrpc
RUN yum -y install zip unzip

# composerのインストール
RUN curl -sS https://getcomposer.org/installer | php
RUN mv composer.phar /usr/local/bin/composer

CMD ["/usr/sbin/httpd","-D","FOREGROUND"]

WORKDIR /var/www/html
apache.conf
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# 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"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
<Directory "/var/www/html">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    AllowOverride None

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

##docker-compose.ymlの修正

  • Dockerの管理ファイルdocker-compose.ymlを修正します。
PS C:\Docker\Gauthk\apache-php> cd ..
PS C:\Docker\Gauth> cp .\docker-compose.yml .\docker-compose_0.yml
PS C:\Docker\Gauth> ls


    ディレクトリ: C:\Docker\Gauth


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     11:57                apache-php
d-----       2018/09/25     10:30                mysql
-a----       2018/09/25     12:05            723 docker-compose.yml
-a----       2018/09/25     10:51            454 docker-compose_0.yml
docker-compose.yml
version: "3"
services:
  web:
    build:
      context: ./apache-php
    ports: 
      - 80:80
    privileged: true
    volumes:
      - "./:/var/www/html"
    container_name: "apache-php"
  db:
    build: ./mysql
    ports:
      - 3307:3306
    environment:
      MYSQL_ROOT_PASSWORD: root
      TZ: Asia/Tokyo
    volumes:
      - ./mysql/mysql_data:/var/lib/mysql
    container_name: "mysql5.7"
  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    ports:
      - 8080:80
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    container_name: "phpmyamin-la"

##Dockerイメージ作成

  • PHPのDockerイメージを作成します。
PS C:\Docker\Gauth> docker-compose build
Building web
Step 1/17 : FROM centos:7.4.1708
 ---> d3949e34634c
Step 2/17 : RUN yum -y update
 ---> Running in ab1c14ee5e24
Loaded plugins: fastestmirror, ovl
Determining fastest mirrors
 * base: ftp.jaist.ac.jp
 * extras: ftp.jaist.ac.jp
 * updates: ftp.jaist.ac.jp
Resolving Dependencies
--> Running transaction check
---> Package acl.x86_64 0:2.2.51-12.el7 will be updated
---> Package acl.x86_64 0:2.2.51-14.el7 will be an update

(省略)

Step 17/17 : WORKDIR /var/www/html
 ---> Running in 914911931e22
Removing intermediate container 914911931e22
 ---> 76572461628d
Successfully built 76572461628d
Successfully tagged gauth_web:latest
Building db
Step 1/5 : FROM mysql:5.7
 ---> 563a026a1511
Step 2/5 : EXPOSE 3306
 ---> Using cache
 ---> 14c5b3522dcb
Step 3/5 : ADD ./my.cnf /etc/mysql/conf.d/my.cnf
 ---> Using cache
 ---> bb0ed17eb1f2
Step 4/5 : RUN chmod 644 /etc/mysql/conf.d/my.cnf
 ---> Using cache
 ---> 62d2c1e30c11
Step 5/5 : CMD ["mysqld"]
 ---> Using cache
 ---> b13e71bd1d84
Successfully built b13e71bd1d84
Successfully tagged gauth_db:latest
phpmyadmin uses an image, skipping
  • 作成したイメージを確認します。
PS C:\Docker\Gauth> docker images
REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
gauth_web                  latest              76572461628d        18 minutes ago      1.16GB
gauth_db                   latest              b13e71bd1d84        3 hours ago         372MB
mysql                      5.7                 563a026a1511        2 weeks ago         372MB
phpmyadmin/phpmyadmin      latest              126b8717cebb        4 weeks ago         166MB
centos                     7.4.1708            d3949e34634c        7 weeks ago         197MB
docker4w/nsenter-dockerd   latest              cae870735e91        11 months ago       187kB

##Dockerコンテナ作成

  • PHPとMySQLとPHP MyAdminのDockerコンテナを起動します。
PS C:\Docker\Gauth> docker-compose up -d
mysql5.7 is up-to-date
phpmyamin-la is up-to-date
Creating apache-php ... done
  • 起動したコンテナを確認します。
PS C:\Docker\Gauth> docker ps
CONTAINER ID        IMAGE                          COMMAND                  CREATED             STATUS              PORTS                               NAMES
f2cbabf9cf23        gauth_web                      "/usr/sbin/httpd -D …"   47 seconds ago      Up 46 seconds       0.0.0.0:80->80/tcp                  apache-php
f78aa9b98c39        phpmyadmin/phpmyadmin:latest   "/run.sh supervisord…"   About an hour ago   Up About an hour    9000/tcp, 0.0.0.0:8080->80/tcp      phpmyamin-la
2798a0df5134        gauth_db                       "docker-entrypoint.s…"   About an hour ago   Up About an hour    33060/tcp, 0.0.0.0:3307->3306/tcp   mysql5.7

##画面表示

  • ブラウザで http://localhost/ へアクセスします。
    WEB画面(apacheのデフォルト画面)が表示されることを確認します。
    全画面キャプチャ 20200502 180535.jpg

##Laravelのプロジェクトを作成する

  • 「g-auth」というプロジェクト名で、Laravelのプロジェクトを作成します。
PS C:\Docker\Gauth> docker-compose exec web composer create-project "laravel/laravel=5.5.*" g-auth
Do not run Composer as root/super user! See https://getcomposer.org/root for details
Installing laravel/laravel (v5.5.28)
  - Installing laravel/laravel (v5.5.28): Downloading (100%)
Created project in g-auth
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 71 installs, 0 updates, 0 removals
  - Installing symfony/thanks (v1.1.0): Downloading (100%)
  - Installing vlucas/phpdotenv (v2.5.1): Downloading (100%)

(省略)

laravel/framework suggests installing symfony/psr-http-message-bridge (Required to psr7 bridging features (~1.0).)
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to work.)
psy/psysh suggests installing hoa/console (A pure PHP readline implementation. You'll want this if your PHP install doesn't already support readline or libedit.)
filp/whoops suggests installing whoops/soap (Formats errors as SOAP responses)
sebastian/global-state suggests installing ext-uopz (*)
phpunit/php-code-coverage suggests installing ext-xdebug (^2.5.5)
phpunit/phpunit suggests installing phpunit/php-invoker (^1.1)
phpunit/phpunit suggests installing ext-xdebug (*)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover
Discovered Package: fideloper/proxy
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Package manifest generated successfully.
> @php artisan key:generate
Application key [base64:S476buAXq0ZpDUtd4aq8bDk+9sLOLqh081thjc2ufcw=] set successfully.
  • 作成したプロジェクト(g-authディレクトリ内)の .env ファイルを修正します。
PS C:\Docker\Gauth\g-auth> ls


    ディレクトリ: C:\Docker\Gauth\g-auth


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/01/04      1:52                app
d-----       2018/01/04      1:52                bootstrap
d-----       2018/01/04      1:52                config
d-----       2018/01/04      1:52                database
d-----       2018/01/04      1:52                public
d-----       2018/01/04      1:52                resources
d-----       2018/01/04      1:52                routes
d-----       2018/01/04      1:52                storage
d-----       2018/01/04      1:52                tests
d-----       2018/09/25     14:15                vendor
-a----       2018/09/25     14:15            616 .env
-a----       2018/01/04      1:52            565 .env.example
-a----       2018/01/04      1:52            111 .gitattributes
-a----       2018/01/04      1:52            146 .gitignore
-a----       2018/01/04      1:52           1686 artisan
-a----       2018/01/04      1:52           1413 composer.json
-a----       2018/09/25     14:15         145721 composer.lock
-a----       2018/01/04      1:52           1125 package.json
-a----       2018/01/04      1:52           1040 phpunit.xml
-a----       2018/01/04      1:52           3550 readme.md
-a----       2018/01/04      1:52            563 server.php
-a----       2018/01/04      1:52            549 webpack.mix.js
.env
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:S476buAXq0ZpDUtd4aq8bDk+9sLOLqh081thjc2ufcw=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
//DB_HOST=127.0.0.1
DB_HOST=mysql5.7

DB_PORT=3306
//DB_DATABASE=homestead
//DB_USERNAME=homestead
//DB_PASSWORD=secret
DB_DATABASE=g_auth
DB_USERNAME=root
DB_PASSWORD=root

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
  • apache-phpディレクトリ内にある apache.conf を修正します。
PS C:\Docker\Gauth\g-auth> cd ..\apache-php\
PS C:\Docker\Gauth\apache-php> ls


    ディレクトリ: C:\Docker\Gauth\apache-php


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       2018/09/25     14:31          11899 apache.conf
-a----       2018/09/25     13:38           1018 Dockerfile
apache.conf
#
# This is the main Apache HTTP server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See <URL:http://httpd.apache.org/docs/2.4/> for detailed information.
# In particular, see
# <URL:http://httpd.apache.org/docs/2.4/mod/directives.html>
# for a discussion of each configuration directive.
#
# Do NOT simply read the instructions in here without understanding
# what they do.  They're here only as hints or reminders.  If you are unsure
# consult the online docs. You have been warned.
#
# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so 'log/access_log'
# with ServerRoot set to '/www' will be interpreted by the
# server as '/www/log/access_log', where as '/log/access_log' will be
# interpreted as '/log/access_log'.

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to specify a local disk on the
# Mutex directive, if file-based mutexes are used.  If you wish to share the
# same ServerRoot for multiple httpd daemons, you will need to change at
# least PidFile.
#
ServerRoot "/etc/httpd"

#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
Listen 80

#
# Dynamic Shared Object (DSO) Support
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
Include conf.modules.d/*.conf

#
# If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.
#
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
User apache
Group apache

# 'Main' server configuration
#
# The directives in this section set up the values used by the 'main'
# server, which responds to any requests that aren't handled by a
# <VirtualHost> definition.  These values also provide defaults for
# any <VirtualHost> containers you may define later in the file.
#
# All of these directives may appear inside <VirtualHost> containers,
# in which case these default settings will be overridden for the
# virtual host being defined.
#

#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
ServerAdmin root@localhost

#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80

#
# Deny access to the entirety of your server's filesystem. You must
# explicitly permit access to web content directories in other
# <Directory> blocks below.
#
<Directory />
    AllowOverride none
    Require all denied
</Directory>

#
# Note that from this point forward you must specifically allow
# particular features to be enabled - so if something's not working as
# you might expect, make sure that you have specifically enabled it
# below.
#

#
# DocumentRoot: The directory out of which you will serve your
# 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/public"

#
# Relax access to content within /var/www.
#
<Directory "/var/www">
    AllowOverride None
    # Allow open access:
    Require all granted
</Directory>

# Further relax access to the default document root:
#※変更する
#<Directory "/var/www/html">
<Directory "/var/www/html/public">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # 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.
    #
    Require all granted
</Directory>

#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
<IfModule dir_module>
    DirectoryIndex index.html
</IfModule>

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<Files ".ht*">
    Require all denied
</Files>

#
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog "logs/error_log"

#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn

<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog "logs/access_log" common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog "logs/access_log" combined
</IfModule>

<IfModule alias_module>
    #
    # Redirect: Allows you to tell clients about documents that used to
    # exist in your server's namespace, but do not anymore. The client
    # will make a new request for the document at its new location.
    # Example:
    # Redirect permanent /foo http://www.example.com/bar

    #
    # Alias: Maps web paths into filesystem paths and is used to
    # access content that does not live under the DocumentRoot.
    # Example:
    # Alias /webpath /full/filesystem/path
    #
    # If you include a trailing / on /webpath then the server will
    # require it to be present in the URL.  You will also likely
    # need to provide a <Directory> section to allow access to
    # the filesystem path.

    #
    # ScriptAlias: This controls which directories contain server scripts.
    # ScriptAliases are essentially the same as Aliases, except that
    # documents in the target directory are treated as applications and
    # run by the server when requested rather than as documents sent to the
    # client.  The same rules about trailing "/" apply to ScriptAlias
    # directives as to Alias.
    #
    ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

</IfModule>

#
# "/var/www/cgi-bin" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Require all granted
</Directory>

<IfModule mime_module>
    #
    # TypesConfig points to the file containing the list of mappings from
    # filename extension to MIME-type.
    #
    TypesConfig /etc/mime.types

    #
    # AddType allows you to add to or override the MIME configuration
    # file specified in TypesConfig for specific file types.
    #
    #AddType application/x-gzip .tgz
    #
    # AddEncoding allows you to have certain browsers uncompress
    # information on the fly. Note: Not all browsers support this.
    #
    #AddEncoding x-compress .Z
    #AddEncoding x-gzip .gz .tgz
    #
    # If the AddEncoding directives above are commented-out, then you
    # probably should define those extensions to indicate media types:
    #
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz

    #
    # AddHandler allows you to map certain file extensions to "handlers":
    # actions unrelated to filetype. These can be either built into the server
    # or added with the Action directive (see below)
    #
    # To use CGI scripts outside of ScriptAliased directories:
    # (You will also need to add "ExecCGI" to the "Options" directive.)
    #
    #AddHandler cgi-script .cgi

    # For type maps (negotiated resources):
    #AddHandler type-map var

    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>

#
# Specify a default charset for all content served; this enables
# interpretation of all content as UTF-8 by default.  To use the
# default browser choice (ISO-8859-1), or to allow the META tags
# in HTML content to override this choice, comment out this
# directive:
#
AddDefaultCharset UTF-8

<IfModule mime_magic_module>
    #
    # The mod_mime_magic module allows the server to use various hints from the
    # contents of the file itself to determine its type.  The MIMEMagicFile
    # directive tells the module where the hint definitions are located.
    #
    MIMEMagicFile conf/magic
</IfModule>

#
# Customizable error responses come in three flavors:
# 1) plain text 2) local redirects 3) external redirects
#
# Some examples:
#ErrorDocument 500 "The server made a boo boo."
#ErrorDocument 404 /missing.html
#ErrorDocument 404 "/cgi-bin/missing_handler.pl"
#ErrorDocument 402 http://www.example.com/subscription_info.html
#

#
# EnableMMAP and EnableSendfile: On systems that support it,
# memory-mapping or the sendfile syscall may be used to deliver
# files.  This usually improves server performance, but must
# be turned off when serving from networked-mounted
# filesystems or if support for these functions is otherwise
# broken on your system.
# Defaults if commented: EnableMMAP On, EnableSendfile Off
#
#EnableMMAP off
EnableSendfile on

# Supplemental configuration
#
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf

#※追加する
LoadModule rewrite_module modules/mod_rewrite.so
  • Dockerの管理ファイルdocker-compose.ymlを修正します。
PS C:\Docker\Gauthk\apache-php> cd ..
PS C:\Docker\Gauth> cp .\docker-compose.yml .\docker-compose_1.yml
PS C:\Docker\Gauth> ls


    ディレクトリ: C:\Docker\Gauth


Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       2018/09/25     14:29                apache-php
d-----       2018/09/25     14:15                g-auth
d-----       2018/09/25     10:30                mysql
-a----       2018/09/25     14:54            723 docker-compose.yml
-a----       2018/09/25     10:51            454 docker-compose_0.yml
-a----       2018/09/25     13:40            629 docker-compose_1.yml
docker-compose.yml
version: "3"
services:
  web:
    build:
      context: ./apache-php
    ports:
      - 80:80
    privileged: true
    links:
      - db
    volumes:
      - "./g-auth/:/var/www/html"
      - "./apache-php/apache.conf:/etc/httpd/conf/httpd.conf"
    container_name: "apache-php"
  db:
    build: ./mysql
    ports:
      - 3307:3306
    environment:
      MYSQL_ROOT_PASSWORD: root
      TZ: Asia/Tokyo
    volumes:
      - ./mysql/mysql_data:/var/lib/mysql
    container_name: "mysql5.7"
  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    ports:
      - 8080:80
    environment:
      - PMA_ARBITRARY=1
      - PMA_HOST=db
    container_name: "phpmyamin-la"
  • コンテナを再起動します。
PS C:\Docker\Gauth> docker-compose down
Stopping phpmyamin-la ... done
Stopping mysql5.7     ... done
Stopping apache-php   ... done
Removing phpmyamin-la ... done
Removing mysql5.7     ... done
Removing apache-php   ... done
Removing network gauth_default
PS C:\Docker\Gauth> docker-compose up -d
Creating network "gauth_default" with the default driver
Creating mysql5.7 ... done
Creating apache-php   ... done
Creating phpmyamin-la ... done

##画面表示

  • ブラウザで http://localhost/ へアクセスします。
    WEB画面(Laravelの初期画面)が表示されることを確認します。
    全画面キャプチャ 20200502 180649.jpg

##Laravelの認証モジュールをインストールする

  • Laravelの認証モジュールをインストールします。
PS C:\Docker\Gauth> docker-compose exec web php artisan make:auth
Authentication scaffolding generated successfully.

PS C:\Docker\Gauth> docker-compose exec web php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table
  • ブラウザで http://localhost/ へアクセスします。

    WEB画面(Laravelの初期画面)が表示されることを確認します。

    画面の右上に「LOGIN」「REGISTER」というリンクが表示されていることを確認します。

    「REGISTER」のリンクをクリックします。
    全画面キャプチャ 20200502 180737.jpg

  • E-Mail Addressの項目には、メールアドレスを入力します。

    その他の項目(Name、Password、Confirm Password)は、任意の値を入力します。

    「Register」ボタンを押下します。
    全画面キャプチャ 20200502 180840.jpg

  • アカウントが登録され、ログイン後画面に遷移します。
    全画面キャプチャ 20200502 180928.jpg

  • ログアウトします。
    全画面キャプチャ 20200502 181021.jpg

  • Laravelの初期画面が表示されます。
    「LOGIN」のリンクをクリックします。
    全画面キャプチャ 20200502 181050.jpg

  • アカウント登録した情報を、E-Mail Address、Passwordに入力し、「Login」ボタンを押下します。
    全画面キャプチャ 20200502 181135.jpg

  • ログイン後画面に遷移します。
    全画面キャプチャ 20200502 181135.jpg

以上となります。

5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?