溫馨提示×

Docker中怎么搭建LNMP環(huán)境

小億
93
2023-11-20 13:32:11
欄目: 編程語言

在Docker中搭建LNMP環(huán)境,需要以下步驟:

  1. 安裝Docker和Docker Compose:根據(jù)操作系統(tǒng)的不同,安裝Docker和Docker Compose。

  2. 創(chuàng)建Docker Compose文件:在項目目錄下創(chuàng)建一個docker-compose.yml文件,并添加以下內(nèi)容:

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
  1. 創(chuàng)建Nginx配置文件:在項目目錄下創(chuàng)建nginx文件夾,并在其中創(chuàng)建nginx.conf文件和conf.d文件夾。
  • 在nginx.conf文件中,可以設置一些全局的Nginx配置,如worker_processes、error_log等。一個簡單的示例:
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文件夾中,可以放置具體的Nginx站點配置文件,如site.conf。一個簡單的示例:
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;
    }
}
  1. 創(chuàng)建PHP代碼文件夾:在項目目錄下創(chuàng)建php文件夾,并將PHP代碼放置在其中。

  2. 啟動LNMP環(huán)境:在項目目錄下運行以下命令啟動LNMP環(huán)境:

docker-compose up -d
  1. 訪問網(wǎng)站:通過瀏覽器訪問http://localhost,即可看到Nginx默認頁面。如果有自己的PHP代碼,可以將代碼放置在php文件夾中,并通過http://localhost/your_php_file.php訪問。

注意:在以上步驟中,需要根據(jù)實際情況修改配置文件中的相關參數(shù),如數(shù)據(jù)庫密碼、數(shù)據(jù)庫名稱、網(wǎng)站域名等。

0