如何在Debian上部署LNMP网站

845
2025/3/21 0:32:43
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Debian上部署LNMP(Linux, Nginx, MySQL/MariaDB, PHP)网站的步骤如下:

1. 更新系统

首先,确保你的Debian系统是最新的:

sudo apt update
sudo apt upgrade -y

2. 安装Nginx

安装Nginx作为Web服务器:

sudo apt install nginx -y

启动Nginx并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

3. 安装MySQL/MariaDB

你可以选择安装MySQL或MariaDB。这里以MariaDB为例:

sudo apt install mariadb-server -y

启动MariaDB并设置开机自启:

sudo systemctl start mariadb
sudo systemctl enable mariadb

运行安全脚本以设置root密码和其他安全选项:

sudo mysql_secure_installation

4. 安装PHP

安装PHP及其常用扩展:

sudo apt install php-fpm php-mysql -y

启动PHP-FPM并设置开机自启:

sudo systemctl start php7.4-fpm
sudo systemctl enable php7.4-fpm

编辑Nginx配置文件以使用PHP-FPM处理PHP文件。打开Nginx默认站点配置文件:

sudo nano /etc/nginx/sites-available/default

找到以下部分并进行修改:

server {
    ...
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
    ...
}

保存并退出编辑器,然后测试Nginx配置:

sudo nginx -t

重新加载Nginx以应用更改:

sudo systemctl reload nginx

5. 配置防火墙

如果你使用的是UFW(Uncomplicated Firewall),允许HTTP和HTTPS流量:

sudo ufw allow 'Nginx Full'

6. 创建数据库和用户

登录到MySQL/MariaDB并创建数据库和用户:

sudo mysql -u root -p

在MySQL shell中执行以下命令:

CREATE DATABASE your_database_name;
CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_username'@'localhost';
FLUSH PRIVILEGES;
EXIT;

7. 部署网站

将你的网站文件上传到服务器上的适当目录(例如 /var/www/html)。你可以使用FTP、SCP或其他文件传输方法。

8. 配置Nginx虚拟主机(可选)

如果你有多个网站,可以为每个网站创建一个单独的Nginx配置文件。例如,创建一个新的配置文件:

sudo nano /etc/nginx/sites-available/your_site

添加以下内容:

server {
    listen 80;
    server_name your_domain.com www.your_domain.com;

    root /var/www/html/your_site;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

启用该站点:

sudo ln -s /etc/nginx/sites-available/your_site /etc/nginx/sites-enabled/

测试Nginx配置并重新加载:

sudo nginx -t
sudo systemctl reload nginx

9. 测试网站

打开浏览器并访问你的域名,确保一切正常运行。

通过以上步骤,你应该能够在Debian上成功部署一个LNMP网站。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Debian Context下如何解决常见故障