在CentOS上配置LNMP(Linux, Nginx, MySQL, PHP)环境并设置MySQL数据库,可以按照以下步骤进行:
1. 安装CentOS操作系统确保你已经安装了CentOS操作系统。如果没有,请先安装。
2. 更新系统sudo yum update -y
3. 安装Nginxsudo yum install nginx -y
启动Nginx并设置开机自启:
sudo systemctl start nginxsudo systemctl enable nginx
4. 安装MySQLCentOS 8默认使用MariaDB,它是MySQL的一个分支。如果你需要安装MySQL,可以使用以下命令:
sudo yum install mysql-server -y
启动MySQL并设置开机自启:
sudo systemctl start mysqldsudo systemctl enable mysqld
5. 安全配置MySQL运行MySQL的安全配置脚本:
sudo mysql_secure_installation
按照提示进行操作,设置root密码,删除匿名用户,禁止root远程登录等。
6. 安装PHPsudo yum install php php-fpm php-mysqlnd -y
启动PHP-FPM并设置开机自启:
sudo systemctl start php-fpmsudo systemctl enable php-fpm
7. 配置Nginx以支持PHP编辑Nginx配置文件,通常位于/etc/nginx/nginx.conf
或/etc/nginx/conf.d/default.conf
:
sudo vi /etc/nginx/conf.d/default.conf
在server块中添加以下内容:
server {listen 80;server_name your_domain.com; # 替换为你的域名或IP地址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;}}
8. 重启Nginxsudo systemctl restart nginx
9. 创建数据库和用户登录MySQL:
sudo mysql -u root -p
创建数据库和用户:
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;
10. 测试PHP连接MySQL在网站根目录下创建一个PHP文件(例如info.php
),内容如下:
<?phpphpinfo();?>
访问http://your_domain.com/info.php
,如果看到PHP信息页面,说明配置成功。
确保防火墙允许HTTP和HTTPS流量:
sudo firewall-cmd --permanent --zone=public --add-service=httpsudo firewall-cmd --permanent --zone=public --add-service=httpssudo firewall-cmd --reload
完成以上步骤后,你的CentOS系统上就成功配置了LNMP环境,并且可以正常运行MySQL数据库。