在在docker容器中使用非容器中使用非root用户执行脚本操作用户执行脚本操作
应用容器化之后,在docker容器启动时,默认使用的是root用户执行命令,因此容器中的应用默认都是使用root用户来运行
的,存在很高的安全风险,那么如何能够使用非root的业务用户来运行应用呢,
下面我将举一个简单的例子来说明。
该例子是在容器中使用自建的用户来运行一个简单的shell脚本,并将脚本输出日志持久到容器外部。接下来让我们来看从制
作镜像到容器运行的全过程吧。
1、构建镜像:、构建镜像:
我将会使用dockerfile的方式来构建镜像,基础镜像使用ubuntu 14.04(需要先拉取该镜像,docker pullubuntu:14.04)。
dockerfile内容如下
[root@host09 test]# cat Dockerfile
FROMdocker.io/ubuntu:14.04
MAINTAINER hepengfei
RUN groupadd hpf --创建用户组
RUN useradd -d /data -g hpf -mhpf --创建用户
RUN su - hpf -c "mkdir -p /data/scripts"
RUN su - hpf -c "mkdir -p /data/logs"
WORKDIR /data/scripts
COPY test.sh /data/scripts/
RUN chown hpf:hpf test.sh
RUN chmod 755 test.sh
ENTRYPOINT su - hpf -c "/data/scripts/test.sh" --使用所创建的用户来运行脚本
[root@host09 test]#
脚本内容如下:
[root@host09 test]# cattest.sh
while [ 1 = 1 ] do
echo `id`>>/data/logs/hpf.log --将日志输出到文件,启动容器的时候做持久化
sleep 1
done
[root@host09 test]#
接下来让我们来构建镜像:
[root@host09 test]# dockerbuild -t hpf:v2 .
Sending build context to Docker daemon 3.072 kB
Step 1 : FROM docker.io/ubuntu:14.04
---> c69811d4e993
Step 2 : MAINTAINER hepengfei
---> Using cache
---> b8401d2eb439
Step 3 : RUN groupadd hpf
---> Using cache
---> 2e0d20802c41
Step 4 : RUN useradd -d /data -g hpf -m hpf
---> Using cache
---> bac36ee97aba
Step 5 : RUN su - hpf -c "mkdir -p /data/scripts"
---> Using cache
---> a92c3f5f8e34
Step 6 : RUN su - hpf -c "mkdir -p /data/logs"
---> Using cache
---> 2e8665da7092
Step 7 : WORKDIR /data/scripts
---> Using cache
---> 7cf84a5a8aca
Step 8 : COPY test.sh /data/scripts/
---> 7e4c24de2096
Removing intermediate container f96358d91c35
Step 9 : RUN chown hpf:hpf test.sh
---> Running in fc9ab290c56c
---> f38afd1ea62c
Removing intermediate container fc9ab290c56c
Step 10 : RUN chmod 755 test.sh
---> Running in a35b507a1527
评论0