DockerでLNMP環境を構築する方法
DockerでLNMP環境を構築するには、以下の手順が必要です。
- OSに応じたDockerとDocker Composeのインストール
- プロジェクトのディレクトリにdocker-compose.ymlファイルを作成し、以下を追加します。
version: '3'
services:
nginx:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/conf.d:/etc/nginx/conf.d
- ./html:/usr/share/nginx/html
depends_on:
- php
php:
image: php:7.4-fpm
volumes:
- ./php:/var/www/html
mysql:
image: mysql:latest
restart: always
environment:
MYSQL_ROOT_PASSWORD: your_password
MYSQL_DATABASE: your_database
MYSQL_USER: your_user
MYSQL_PASSWORD: your_password
volumes:
- ./mysql:/var/lib/mysql
- プロジェクトのルートディレクトリに nginx ディレクトリを作成し、そのディレクトリ内に nginx.conf ファイルと conf.d ディレクトリを作成します。
- nginx.confファイルには、worker_processes や error_log といった nginx のグローバル設定を設定できます。ちょっとした例:
worker_processes 1;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm index.php;
}
location ~ \.php$ {
root /var/www/html;
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
}
- conf.d フォルダには、site.conf といった Nginx 固有のサイト設定ファイルを置くことができます。簡単な例を以下に示します。
server {
listen 80;
server_name example.com;
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
- プロジェクトディレクトリにphpフォルダを作成し、そこにPHPコードを格納するフォルダを作成します。
- LNMP環境の起動: プロジェクトディレクトリで以下の命令を実行してLNMP環境を起動します:
docker-compose up -d
- Webサイトへアクセスする:ブラウザ経由で http://localhost にアクセスすると、Nginx の初期ページが表示されます。自分の PHP コードがある場合は、php フォルダにコードを配置し、http://localhost/your_php_file.php からアクセスできます。
注意:前の手順では、データベースのパスワード、データベース名、ウェブサイトのドメイン名などの関連パラメーターを実際の状況に基づいて設定ファイルで変更する必要があります。