在 Debian 12 上手动安装 LEMP

LEMP 是用于 Web 应用程序开发和托管的流行软件包。它由四个关键组件组成:Linux、Nginx、MySQL 或 MariaDB, 以及 PHP。Linux是操作系统,Nginx 是处理 HTTP 请求和提供静态内容(如图像和 CSS 文件)的 Web 服务器。MySQL 或 MariaDB 被用作数据库系统。PHP 是用于生成 Web 内容并与数据库进行动态交互的脚本语言。这些组件形成了一个强大且可扩展的环境,用于构建和部署网站和Web应用程序。

前置条件

  • 一台运行Debian 12的服务器。
  • 一个具有 sudo 特权的非 root 用户(参考:使用 sudo 替代直接以 root 用户执行命令)。
  • 一个指向服务器的域名(FQDN),例如 example.com。
  • 启用并运行了 UFW。
  • 所有组件都已更新:
sudo apt update && sudo apt upgrade
  • 您系统需要的一些软件包:
sudo apt install wget curl nano ufw software-properties-common dirmngr apt-transport-https gnupg2 ca-certificates lsb-release debian-archive-keyring unzip -y

第一步:配置防火墙

在安装任何软件包之前的第一步是配置防火墙以允许 HTTP 和 HTTPS 连接。

检查防火墙的状态:

sudo ufw status

您应该看到类似以下的内容:

Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)

开放 HTTP 和 HTTPS 端口:

sudo ufw allow http
sudo ufw allow https

再次检查防火墙状态:

sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
OpenSSH (v6)               ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)
443/tcp (v6)               ALLOW       Anywhere (v6)

第二步:安装 PHP

Debian 12 的软件源默认安装 是 PHP 8.2。运行以下命令来安装:

sudo apt install php-fpm php-cli php-mysql php-mbstring php-xml php-gd

我们已经安装了 PHP 的 MySQL、CLI、GD、Mbstring 和 XML 扩展。您可以根据您的需求安装任何额外的扩展。

检查安装的 PHP 版本:

php --version
PHP 8.2.7 (cli) (built: Jun  9 2023 19:37:27) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.7, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.7, Copyright (c), by Zend Technologies

第三步:安装 MariaDB

Debian 12 默认情况下不包含 MySQL,并且他们还没有发布官方的 MySQL 软件包。因此,我们将使用 MariaDB,使用以下命令来安装:

sudo apt install mariadb-server

检查 MariaDB(MySQL)的版本:

mysql --version
mysql  Ver 15.1 Distrib 10.11.3-MariaDB, for debian-linux-gnu (x86_64) using  EditLine wrapper

运行 MariaDB 的安全安装脚本:

sudo mysql_secure_installation

将会要求输入数据库的 root 用户密码。直接按下 回车键,因为我们尚未为其设置密码:

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
haven't set the root password yet, you should just press enter here.

Enter current password for root (enter for none):

接下来,将会询问否要切换到 unix_socket 身份验证方法。unix_socket 插件允许您使用操作系统凭据连接到 MariaDB 服务器。由于您已经有一个受保护的 root 账户,输入 n 继续。

K, successfully used password, moving on...

Setting the root password or using the unix_socket ensures that nobody
can log into the MariaDB root user without the proper authorisation.

You already have your root account protected, so you can safely answer 'n'.

Switch to unix_socket authentication [Y/n] n

接下来,将会询问您是否要更改根密码。在 Debian 12 上,root 密码与自动系统维护密切相关,因此不应该被更改。输入 n 继续。

 ... skipping.

You already have your root account protected, so you can safely answer 'n'.

Change the root password? [Y/n] n

接下来,您将被问及一些问题,以提高 MariaDB 的安全性。输入 Y 来移除匿名用户、禁止远程 root 用户登录、移除测试数据库,并重新加载权限表。

 ... skipping.

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

您可以在命令行中输入 sudo mysqlsudo mariadb 来进入 MariaDB 的命令行界面。

登录进 MariaDB:

sudo mysql

添加 MariaDB 管理账号:

GRANT ALL ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
exit

第四步:安装 NGINX

Debian 12 默认软件源中的 Nginx 版本比较旧。因此需要从 Nginx 官方的软件源中安装。

导入 Nginx 的签名密钥:

curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

添加 Nginx 的稳定版本软件源:

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/debian `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

更新系统软件源:

sudo apt update

安装 Nginx:

sudo apt install nginx

验证安装。在 Debian 系统上,以下命令只能在使用 sudo 时运行:

sudo nginx -v
nginx version: nginx/1.24.0

启动 Nginx:

sudo systemctl start nginx

检查服务状态:

sudo systemctl status nginx
? nginx.service - nginx - high performance web server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Thu 2023-06-15 16:33:46 UTC; 1s ago
       Docs: https://nginx.org/en/docs/
    Process: 2257 ExecStart=/usr/sbin/nginx -c /etc/nginx/nginx.conf (code=exited, status=0/SUCCESS)
   Main PID: 2258 (nginx)
      Tasks: 2 (limit: 1108)
     Memory: 1.8M
        CPU: 6ms
     CGroup: /system.slice/nginx.service
             ??2258 "nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf"
             ??2259 "nginx: worker process"

第五步:配置 PHP-FPM

更改 upload_max_filesize 和 post_max_size 变量的值,以便设置文件上传大小:

sudo sed -i 's/post_max_size = 8M/post_max_size = 50M/' /etc/php/8.2/fpm/php.ini
sudo sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 50M/' /etc/php/8.2/fpm/php.ini

根据服务器资源和要求配置 PHP 的内存限制,例如配置成 256M:

sudo sed -i 's/memory_limit = 128M/memory_limit = 256M/' /etc/php/8.2/fpm/php.ini

我们需要将 PHP 进程的 Unix 用户和用户组都设置为 nginx。打开 /etc/php/8.0/fpm/pool.d/www.conf 文件:

sudo vi /etc/php/8.2/fpm/pool.d/www.conf

在文件中找到 user=www-datagroup=www-data 行,并将它们更改为 nginx:

...
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = nginx
group = nginx
...

此外,在文件中找到 listen.owner=www-datalisten.group=www-data 行,并将它们更改为 nginx:

listen.owner = nginx
listen.group = nginx

通过按下 Ctrl + X 并在提示时输入 Y 来保存文件。

重启 php-fpm 服务:

sudo systemctl restart php8.2-fpm

第六步:安装 phpMyAdmin

phpMyAdmin 下载页面 中获取最新版本的 phpMyAdmin 下载链接,建议是 tar.gz 格式的,右键复制,然后下载:

wget https://files.phpmyadmin.net/phpMyAdmin/5.2.1/phpMyAdmin-5.2.1-all-languages.tar.gz

创建一个用于 phpMyAdmin 网站的目录:

sudo mkdir /var/www/html/example.com -p

将 phpMyAdmin 压缩包解压到公共目录中:

sudo tar -xzf phpMyAdmin-5.2.1-all-languages.tar.gz -C /var/www/html/example.com

进入 phpMyAdmin 的网站目录:

cd /var/www/html/example.com

将解压后的目录重命名为某个不容易猜到的名称,以提高安全性,例如 sm175:

sudo mv phpMyAdmin-5.2.1-english sm175

第七步:配置 phpMyAdmin

复制示例配置文件:

sudo cp sm175/config.sample.inc.php sm175/config.inc.php

编辑配置文件:

sudo nano sm175/config.inc.php

找到 $cfg['blowfish_secret'] = ''; 这一行,并输入一个 32 字符的随机字符串,用于基于Cookie的认证。可以使用 phpSolved 的在线Blowfish生成器 生成。

复制该值并粘贴:

$cfg['blowfish_secret'] = 'Tc/HfLPBOAPxJ-rhQP}HJoZEK69c3j:m';

按下 Ctrl + X 并在提示时输入 Y 保存文件。

更改网站和 phpMyAdmin 的所有权为 nginx 用户:

sudo chown -R nginx:nginx /var/www/html/example.com

删除 phpMyAdmin 的安装目录:

sudo rm -rf /var/www/html/example.com/sm175/setup

第八步:配置 Opcache

Opcache 是 PHP 的缓存系统。它通过将预编译的脚本字节码保存在内存中,以便每当用户访问页面时,加载速度更快。Opcache 默认已安装。要进行验证,请检查 PHP 的版本。

php --version
PHP 8.2.7 (cli) (built: Jun  9 2023 19:37:27) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.7, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.7, Copyright (c), by Zend Technologies

如果没有显示 OPcache 相关字样,可以通过运行以下命令手动安装:

sudo apt install php-opcache

编辑 /etc/php/8.2/fpm/conf.d/10-opcache.ini 文件:

sudo nano /etc/php/8.2/fpm/conf.d/10-opcache.ini

在文件中添加以下配置一般会获得更好的性能:

opcache.enable_cli=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60

按下 Ctrl + X 并在提示时输入 Y 保存文件。

重启 php-fpm:

sudo systemctl restart php8.2-fpm

第九步:安装 Certbot

我们需要安装 Certbot 以获取由 Let’s Encrypt 提供的免费 SSL 证书。

您可以选择使用 Debian 的软件源安装 Certbot,或者使用 snapd 工具获取最新版本。我们将使用 snapd 版本。

安装 snapd 软件包:

sudo apt install snapd

确保 snapd 是最新版本:

sudo snap install core
sudo snap refresh core

安装 Certbot:

sudo snap install --classic certbot

使用以下命令创建一个符号链接到 /usr/bin 目录,以确保可以运行 Certbot 命令:

sudo ln -s /snap/bin/certbot /usr/bin/certbot

验证 Certbot 是否安装成功:

certbot --version
certbot 2.6.0

其他说明

1. 使用 Certbot 获取免费 SSL 证书:

sudo certbot certonly --nginx --agree-tos --no-eff-email --staple-ocsp --preferred-challenges http -m name@example.com -d example.com

上述命令将在服务器上将证书下载到 /etc/letsencrypt/live/example.com 目录中,请自行修改邮箱和域名。

2. 生成一个 Diffie-Hellman 组证书:

sudo openssl dhparam -dsaparam -out /etc/ssl/certs/dhparam.pem 4096

Diffie-Hellman 算法可以提高 SSL/TLS 的安全性,因为它可以在客户端和服务器之间安全地交换密钥,从而确保数据的机密性和完整性。Diffie-Hellman 算法可以减少密码分析攻击的可能性,因为它可以动态生成密钥而不是直接使用预定义的密钥。

3. 示例 nginx 站点配置:

server {
    listen       443 ssl http2;
    listen       [::]:443 ssl http2;
    server_name  example.com;

    access_log  /var/log/nginx/example.com.access.log;
    error_log   /var/log/nginx/example.com.error.log;

    ssl_certificate      /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key  /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;

    ssl_session_timeout  5m;
    ssl_session_cache shared:MozSSL:10m;
    ssl_session_tickets off;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_ecdh_curve X25519:prime256v1:secp384r1:secp521r1;
    ssl_stapling on;
    ssl_stapling_verify on;
    ssl_dhparam /etc/ssl/certs/dhparam.pem;

    root /var/www/html/example.com;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Pass PHP Scripts To FastCGI Server
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock; #depends on PHP versions
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

# enforce HTTPS
server {
    listen       80;
    listen       [::]:80;
    server_name  example.com;
    return 301   https://$host$request_uri;
}

自行修改域名、网站目录相关配置。

来源:https://www.howtoforge.com/how-to-install-lemp-stack-nginx-php-and-mariadb-on-debian-12/

《在 Debian 12 上手动安装 LEMP》有2个想法

  1. 这篇文章让我想起自己折腾movabletype博客程序时,从头开始配置一台vps的经历。我是从php、mysql、nginx逐个配置的。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注