You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Docker容器端口绑定域名,无需输入端口即可访问站点?

配置方案

方案一:直接映射宿主机80端口到容器(推荐,配置最简单)

  • 第一步:修改docker-compose.yml的端口映射规则,将原8000端口绑定改为宿主机80端口绑定:
webserver:
  image: nginx:alpine
  container_name: webserver
  restart: unless-stopped
  tty: true
  ports:
  - "80:80" # 把原来的8000:80改成80:80
  - "443:443" # 后续要配HTTPS的话可以把8443改成443
  volumes:
  - ./:/var/www/docker/example/api
  - ./nginx/conf.d/:/etc/nginx/conf.d/
  • 第二步:修改本地./nginx/conf.d/目录下的Nginx配置,修正路径不匹配问题,同时补充Laravel必需的伪静态规则,否则非首页路由会报404:
server {
    listen 80;
    index index.php index.html;
    server_name example.com; # 替换成你实际使用的域名
    error_log  /var/log/nginx/error.log;
    access_log /var/log/nginx/access.log;
    root /var/www/docker/example/api/public; # 修正为和挂载路径匹配的public目录

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

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}
  • 第三步:检查宿主机80端口占用情况,确保没有其他服务(比如宿主机自带的Nginx、Apache)占用80端口,如有占用先停止对应服务:
    执行命令lsof -i:80查看占用进程,如果是系统自带Nginx可以执行systemctl stop nginx关闭,不需要开机启动的话额外执行systemctl disable nginx
  • 第四步:放行服务器80端口的访问权限:
    执行命令ufw allow 80/tcp,如果使用了云服务商的安全组,也要在安全组规则里放行80端口
  • 第五步:将你的域名的A记录解析到Ubuntu服务器的公网IP
  • 第六步:重启Docker服务生效配置:
    执行命令docker-compose up -d --force-recreate webserver
    配置完成后直接访问http://你的域名即可正常打开站点。

方案二:宿主机Nginx反向代理(适用于宿主机80端口被其他服务占用,无法直接映射给Docker的场景)

  • 第一步:保持原有的docker-compose.yml端口映射规则不变(保留8000:80的配置)
  • 第二步:在宿主机上安装Nginx,新增一个站点配置文件:
server {
    listen 80;
    server_name example.com; # 替换成你实际使用的域名
    access_log /var/log/nginx/example_access.log;
    error_log /var/log/nginx/example_error.log;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
  • 第三步:同样完成域名解析、防火墙放行80端口的操作,然后执行systemctl restart nginx重启宿主机Nginx即可生效。

内容的提问来源于stack exchange,提问作者Mehrdad Masoumi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 19:54:05