Oracle云 – golang的HTTP服务器在端口80上无法工作。

huangapple go评论73阅读模式
英文:

Oracle cloud - golang http server not working on port 80

问题

我有一个使用golang编写的HTTP服务器,应该监听端口80

我的问题是:

程序编译正常,但是没有监听任何端口就退出了。当我将端口更改为8080时,一切正常,我可以访问我的网页。

  • 我使用Ubuntu作为操作系统。
  • 我添加了一个允许端口80的入口规则。

我不明白为什么我的服务器不在端口80上监听,而在其他所有端口上都监听。

谢谢你的帮助。

package main

import (
	"fmt"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "<p>Hello world!</p>")
}

func main() {
	http.HandleFunc("/", hello)
	http.ListenAndServe(":80", nil)
}
英文:

I have a golang http server which is supposed to listen on port 80.

My problem is:

The program compiles normally but exit without listening. When I change the port to 8080 everything works normally and I can access my web page.

  • I am using Ubuntu as my operating system.
  • I added an Ingress Rules which allows port 80

I don't understand why my server is not listening on port 80 but listening on all other ports.

Thank you for your help.

package main

import (
	&quot;fmt&quot;
	&quot;net/http&quot;
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, &quot;&lt;p&gt;Hello world!&lt;/p&gt;&quot;)
}

func main() {
		http.HandleFunc(&quot;/&quot;, hello)
		http.ListenAndServe(&quot;:80&quot;, nil)
}

答案1

得分: 1

检查错误

err := http.ListenAndServe(":80", nil)
fmt.Println(err)

我本地的输出是这样的,但也可能有其他原因

listen tcp :80: bind: permission denied
英文:

Check for the error

err := http.ListenAndServe(&quot;:80&quot;, nil)
fmt.Println(err)

output on my local is this, but it can have other reason

listen tcp :80: bind: permission denied

答案2

得分: 1

端口80是一个保留/特殊端口,在许多Linux/Unix系统上必须通过root级别用户访问。您需要以root/wheel组/sudo用户的身份运行它。或者您可以在8080上运行它,并通过具有systemd中root级别权限的类似nginx的工具进行反向代理。这是Web应用程序和代理转发的常见使用模式。

我建议不要将您的golang二进制文件以root身份运行,除非为运行为root的用户设置了其他保护措施,否则这样做是不安全的。

nginx代码片段:

  location / {
    proxy_pass http://0.0.0.0:8080;
}

要确认这是否是问题,您可以使用sudo ./mybinary运行它,并确认它是否正常工作并监听端口80。

英文:

Port 80 is a reserved / special port that must be accessed via root level users on many if not all Linux / Unix systems. You would need to run it as a root / wheel group / sudo user. Or you could run it on 8080 and reverse proxy via something that does have root level at systemd like nginx or similar. This is a common usage pattern for web applications and proxy forwarding.

I would advise against having your golang binary run as root as this is not secure at all without other safeguards in place for that user that is running as root.

nginx snippet:

  location / {
    proxy_pass http://0.0.0.0:8080;
}

To confirm that this is the issue, you can run it as sudo ./mybinary and confirm that it works and listens on 80.

huangapple
  • 本文由 发表于 2021年10月20日 19:56:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/69645568.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定