安装 Nginx(Linux / Mac / Windows / Docker)

阅读:16 2025-07-10

📌 一、Linux 安装(推荐方式)

✅ 1. 使用包管理器安装

【CentOS / RHEL(基于 yum)】

sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

【Debian / Ubuntu(基于 apt)】

sudo apt update
sudo apt install nginx
sudo systemctl start nginx
sudo systemctl enable nginx

🔍 检查是否安装成功

nginx -v   # 查看版本curl http://localhost   # 查看是否返回 Welcome 页面

🌐 默认配置文件路径为:
/etc/nginx/nginx.conf
站点默认目录为:/usr/share/nginx/html


📌 二、Mac 安装(适合开发环境)

✅ 1. 使用 Homebrew 安装

brew install nginx

安装后输出内容类似:

nginx has been installed to:  /opt/homebrew/bin/nginx

✅ 2. 启动 Nginx

sudo nginx

默认站点位置:/opt/homebrew/var/www
默认配置文件:/opt/homebrew/etc/nginx/nginx.conf

🔄 常用命令

sudo nginx -s reload     # 重载配置sudo nginx -s stop       # 停止 Nginxsudo nginx -t            # 检查配置是否正确

📌 三、Windows 安装(适合学习/测试)

虽然 Nginx 官方支持 Windows,但在生产环境中 不推荐使用 Windows 跑 Nginx。这里只用于本地测试。

✅ 1. 下载并解压

✅ 2. 启动服务

双击运行命令或在 cmd 中:

cd C:\nginx
start nginx

📁 默认配置文件路径:C:\nginx\conf\nginx.conf

🔄 管理命令

nginx -s reload     # 重载配置
nginx -s stop       # 停止服务
nginx -t            # 检查语法

📌 四、Docker 安装(适合微服务 / 隔离环境)

适用于任何操作系统(Mac、Linux、Win)使用 Docker 环境运行。

✅ 1. 运行官方容器

docker run --name my-nginx -p 80:80 -d nginx

这样你就可以通过浏览器访问 http://localhost 看到欢迎页了。

✅ 2. 使用挂载方式自定义配置/网站内容

docker run --name my-nginx \
  -p 8080:80 \
  -v $(pwd)/html:/usr/share/nginx/html \
  -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf \
  -d nginx

✅ 3. 进入容器管理

docker exec -it my-nginx /bin/bash

🧠 常见问题排查

问题原因解决方式
nginx: [emerg] bind() to 0.0.0.0:80 failed端口被占用sudo lsof -i :80 查看占用进程并 kill
403 Forbidden无权限访问检查根目录权限
502 Bad Gateway后端未启动或配置错误检查代理配置与后端服务状态


📎 小结

系统推荐安装方式
Linux包管理器(apt/yum)
MacHomebrew
Windows下载 zip 解压运行
通用Docker 容器运行


声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!