Docker用户切换
Docker镜像多数仅包含root用户,且设置容器以root身份启动。如果想要以其他用户身份启动容器,需要保证镜像中含有其他用户,并在容器启动时指定用户。
镜像构建
- 方法一:使用Dockerfile重新构建包含其他用户的镜像。
- 方法二:在目标容器中添加其他用户后,再打包成镜像。以由
root
用户添加ubuntu
用户为例。useradd -d "/home/ubuntu" -m -s "/bin/bash" ubuntu -u 1002 echo 'ubuntu:12345678' | chpasswd
指定用户启动
使用docker-compose启动
version: '3.5'
services:
dgl_cluster:
container_name: dgl_cluster
image: dgl_single:v1.0
user: "dgl"
stdin_open: true
tty: true
command: /bin/bash
用户切换
当容器以非root用户身份启动时,若需要运行某些需要root权限的命令,则需要先切换成root用户,并在命令执行后切换回来。以启动sshd
为例。
- 使用expect命令编写
/home/dgl/.ssh/sshd.sh
脚本#!/bin/bash expect <<-EOF set timeout -1 spawn su root expect "Password:" send "12345678\r" expect "#" send "chown pbg:pbg -R /home/pbg/MyWorkspace\r" expect "#" send "/usr/sbin/sshd\r" expect "#" send "exit\r" expect eof EOF
使用
apt install expect
进行安装 - 在容器启动时启动脚本
version: '3.5' services: dgl_cluster: container_name: dgl_cluster image: dgl_single:v1.0 user: "dgl" stdin_open: true tty: true command: /bin/bash -c "/bin/bash /home/dgl/.ssh/sshd.sh && /bin/bash"