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

运行Docker镜像时无法以www-data用户启动SSH服务,求解决方案

问题描述

我正在进行个人项目开发,使用ubuntu:latest作为基础镜像。已安装包括OpenSSH server在内的所有组件,但以www-data用户执行service ssh start时无法启动SSH服务。

相关配置

sshd_config

Port            2222
ListenAddress       0.0.0.0
LoginGraceTime      180
X11Forwarding       yes
Ciphers aes128-cbc,3des-cbc,aes256-cbc,aes128-ctr,aes192-ctr,aes256-ctr
MACs hmac-sha1,hmac-sha1-96
StrictModes         yes
SyslogFacility      DAEMON
PasswordAuthentication  yes
PermitEmptyPasswords    no
PermitRootLogin     yes
Subsystem sftp internal-sftp

Dockerfile

FROM ubuntu:latest


#Copy Entrypoint.sh
COPY entrypoint.sh /home/

# # # # Start and enable SSH
   RUN apt-get update \
       && apt-get install -y --no-install-recommends dialog \
       && apt-get install -y --no-install-recommends openssh-server \
       && echo "root:<somepassword>" | chpasswd \
       && chmod u+x /home/entrypoint.sh  

COPY /etc/ssh/sshd_config /etc/ssh/

EXPOSE 8000 2222

ENTRYPOINT [ "/home/entrypoint.sh" ]

# Change current user to www-data
USER www-data

# Expose port 9000 and start php-fpm server
EXPOSE 9000

entrypoint.sh

#!/bin/sh
set -e
service ssh start
exec "$@"

错误信息

2023-05-25 16:30:02 start-stop-daemon: unable to set gid to 0 (Operation not permitted)
2023-05-25 16:30:02  * Starting OpenBSD Secure Shell server sshd
2023-05-25 16:30:02    ...fail!

核心问题:如何以www-data用户启动SSH服务?


解决方案

SSH服务启动过程中,start-stop-daemon需要切换到root权限完成初始化操作,非特权用户www-data无法完成这个步骤。以下是几种可行的解决思路:

方法1:给容器添加必要特权(快速临时解决)

启动容器时添加权限参数,让www-data拥有切换gid/uid的权限:

docker run --cap-add=SETUID --cap-add=SETGID 你的镜像名称

方法2:先以root启动SSH,再切换到www-data运行应用(推荐)

这种方式既保证SSH能正常启动,又能让业务服务以非root用户运行,符合安全规范:

  1. 调整Dockerfile:移除提前切换到www-data的命令,保持容器默认以root启动entrypoint
    FROM ubuntu:latest
    
    #Copy Entrypoint.sh
    COPY entrypoint.sh /home/
    
    # 安装组件并配置权限
    RUN apt-get update \
        && apt-get install -y --no-install-recommends dialog openssh-server \
        && echo "root:<somepassword>" | chpasswd \
        && chmod u+x /home/entrypoint.sh \
        && chown -R www-data:www-data /var/run/sshd
    
    COPY sshd_config /etc/ssh/
    
    EXPOSE 8000 2222 9000
    
    ENTRYPOINT [ "/home/entrypoint.sh" ]
    
  2. 修改entrypoint.sh:先以root启动SSH,再切换到www-data执行业务命令(比如php-fpm)
    #!/bin/sh
    set -e
    
    # 以root启动SSH服务
    service ssh start
    
    # 切换到www-data用户执行后续命令
    exec su - www-data -c "$*"
    

方法3:直接用sshd命令启动(绕开service脚本)

跳过service命令,直接调用sshd并指定运行用户,但仍需root权限启动:

sshd -D -f /etc/ssh/sshd_config -o User=www-data

你可以把这条命令替换entrypoint里的service ssh start,同时保证容器以root启动entrypoint,启动后再切换到www-data运行应用。

额外建议

Docker设计理念是一个容器运行一个服务,建议用docker-compose把SSH和php-fpm拆分成两个独立容器,这样权限管理更清晰,也更容易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 20:52:47