温馨提示×

centos lnmp如何配置数据库

小樊
41
2025-12-07 19:49:20
栏目: 智能运维

在CentOS上配置LNMP(Linux, Nginx, MySQL/MariaDB, PHP)环境并设置数据库,可以按照以下步骤进行:

1. 安装Nginx

首先,安装Nginx作为Web服务器。

sudo yum install epel-release
sudo yum install nginx

启动Nginx并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

2. 安装MySQL/MariaDB

接下来,安装MySQL或MariaDB作为数据库服务器。这里以MariaDB为例。

sudo yum install mariadb-server mariadb

启动MariaDB并设置开机自启:

sudo systemctl start mariadb
sudo systemctl enable mariadb

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

sudo mysql_secure_installation

3. 安装PHP

安装PHP及其相关模块。

sudo yum install php php-fpm php-mysqlnd

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

sudo systemctl start php-fpm
sudo systemctl enable php-fpm

4. 配置Nginx以支持PHP

编辑Nginx配置文件以支持PHP处理。

sudo vi /etc/nginx/conf.d/default.conf

server块中添加以下内容:

server {
    listen 80;
    server_name your_domain.com;

    root /var/www/html;
    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-fpm/php-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

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

sudo nginx -t
sudo systemctl restart nginx

5. 创建数据库和用户

登录到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;

6. 配置PHP连接数据库

创建一个PHP文件来测试数据库连接。

sudo vi /var/www/html/index.php

添加以下内容:

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database_name";

// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

保存并退出编辑器,然后在浏览器中访问你的服务器地址(例如 http://your_domain.com),你应该会看到“Connected successfully”的消息。

7. 配置防火墙

确保防火墙允许HTTP和HTTPS流量。

sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload

8. 配置SELinux(可选)

如果SELinux处于 enforcing 模式,可能需要配置它以允许Nginx访问PHP-FPM。

sudo setsebool -P httpd_can_network_connect_db 1

完成以上步骤后,你的CentOS服务器上应该已经成功配置了LNMP环境,并且可以连接和使用数据库了。

0