douling1936 2015-06-19 15:50
浏览 38
已采纳

将Golang作为www-data运行

When I run a Node HTTP server app I usually call a custom function

function runAsWWW()
{
 try 
 {
  process.setgid('www-data');
  process.setuid('www-data');
 } catch (err) 
 {
  console.error('Cowardly refusal to keep the process alive as root.');
  process.exit(1);
 }
}

from server.listen(8080,'localhost',null,runAsWWW);

so the server is actually running as the www-data user to offer a better modicum of security. Is there something similar I can do when I start up a Golang web server by issuing go run index.go?

  • 写回答

4条回答 默认 最新

  • doujiyong7604 2015-06-20 05:39
    关注

    Expanding on @JimB's answer:

    Use a process supervisor to run your application as a specific user (and handle restarts/crashes, log re-direction, etc). setuid and setgid are universally bad ideas for multi-threaded applications.

    Either use your OS' process manager (Upstart, systemd, sysvinit) or a standalone process manager (Supervisor, runit, monit, etc).

    Here's an example for Supervisor:

    [program:yourapp]
    command=/home/yourappuser/bin/yourapp # the location of your app
    autostart=true
    autorestart=true
    startretries=10
    user=yourappuser # the user your app should run as (i.e. *not* root!)
    directory=/srv/www/yourapp.com/ # where your application runs from
    environment=APP_SETTINGS="/srv/www/yourapp.com/prod.toml" # environmental variables
    redirect_stderr=true
    stdout_logfile=/var/log/supervisor/yourapp.log # the name of the log file.
    stdout_logfile_maxbytes=50MB
    stdout_logfile_backups=10
    

    Further: if you're not reverse proxying and your Go application needs to bind to a port < 1024 (e.g. port 80 or 443) then use setcap - for example: setcap cap_net_bind_service=+ep /home/yourappuser/bin/yourapp

    PS: I wrote a little article on how to run Go applications with Supervisor (starting from "I don't have Supervisor installed").

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像