注意:此答案中的几乎所有内容都需要根据您的具体情况进行定制。这是在假设您的 Go 应用程序名为“myapp”并且您已使其侦听端口 8001(以及许多其他端口)的情况下编写的。
您应该制作一个systemd 单元文件,以使您的应用在启动时自动启动。将以下内容放入/etc/systemd/system/myapp.service(根据您的需要调整):
[Unit]
Description=MyApp webserver
[Service]
ExecStart=/www/myapp/bin/webserver
WorkingDirectory=/www/myapp
EnvironmentFile=-/www/myapp/config/myapp.env
StandardOutput=journal
StandardError=inherit
SyslogIdentifier=myapp
User=www-data
Group=www-data
Type=simple
Restart=on-failure
[Install]
WantedBy=multi-user.target
有关这些设置的文档,请参阅:man systemd.unit、man systemd.service 和 man systemd.exec
开始吧:
systemctl start myapp
检查是否正常:
systemctl status myapp
启用自动启动:
systemctl enable myapp
然后是时候为您的应用程序配置 Apache 虚拟主机了。将以下内容放入/etc/apache2/sites-available/myapp.conf:
<VirtualHost *:80>
ServerName myapp.example.com
ServerAdmin webmaster@example.com
DocumentRoot /www/myapp/public
ErrorLog ${APACHE_LOG_DIR}/myapp-error.log
CustomLog ${APACHE_LOG_DIR}/myapp-access.log combined
ProxyPass "/" "http://localhost:8001/"
</VirtualHost>
代理相关设置文档:https://httpd.apache.org/docs/2.4/mod/mod_proxy.html
启用配置:
a2ensite myapp
确保您没有在 Apache 配置中出错:
apachectl configtest
如果代理模块之前未启用,此时您将收到错误消息。在这种情况下,启用代理模块并重试:
a2enmod proxy
a2enmod proxy_http
apachectl configtest
重新加载 Apache 配置:
systemctl reload apache2
记得让名称myapp.example.com 在 DNS 中可用。
就是这样!
编辑:添加了指向文档的指针和启用 Apache 模块的说明(如果需要)。使用 apachectl 进行配置测试。