本文介绍了添加交互式用户输入,例如 Docker 容器中的“读取"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个可以执行以下操作的 Docker 镜像:

I want to make a Docker image that can perform the following:

  1. 使用read
  2. 获取用户输入并将其存储在局部变量中
  3. 将该变量用于以后的命令

使用它我有以下 Dockerfile:

Using that I have the following Dockerfile:

FROM ubuntu
RUN ["echo", "'Input something: '"]
RUN ["read", "some_var"]
RUN ["echo", "You wrote $some_var!"]

在运行 docker build 时,会产生以下输出:

which, when running docker build, yields the following output:

Sending build context to Docker daemon  3.072kB
Step 1/4 : FROM ubuntu
 ---> 4e2eef94cd6b
Step 2/4 : RUN ["echo", "'Input something: '"]
 ---> Using cache
 ---> a9d967721ade
Step 3/4 : RUN ["read", "some_var"]
 ---> Running in e1c603e2d376
OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"read\": executable file not found in $PATH": unknown

read 似乎是一个内置的 bash 函数";因为 which read 没有产生任何结果.我将 ["read", "some_var"] 替换为 ["/bin/bash -c read", "some_var"][/bin/bash"、-c"、read"、some_var"] 但都产生以下结果:

read seems to be a built-in bash "function" since which read yields nothing.I replaced ["read", "some_var"] with ["/bin/bash -c read", "some_var"] and ["/bin/bash", "-c", "read", "some_var"] but both yield the following:

...
Step 3/4 : RUN ["/bin/bash -c read", "some_var"]
 ---> Running in 6036267781a4
OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"/bin/bash -c read\": stat /bin/bash -c read: no such file or directory": unknown
...
Step 3/4 : RUN ["/bin/bash", "-c", "read", "some_var"]
 ---> Running in 947dda3a9a6c
The command '/bin/bash -c read some_var' returned a non-zero code: 1

此外,我还用 RUN read some_var 替换了它,但结果如下:

In addition, I also replaced it with RUN read some_var but which yields the following:

...
Step 3/4 : RUN read some_var
 ---> Running in de0444c67386
The command '/bin/sh -c read some_var' returned a non-zero code: 1

谁能帮我解决这个问题?

Can anyone help me with this?

推荐答案

一种解决方案是使用外部 shell 脚本并使用 入口点.

One solution is to use an external shell script and use ENTRYPOINT.

run.sh 的内容:

#!/bin/bash
echo "Input something!"
read some_var
echo "You wrote ${some_var}!"

Dockerfile 的内容:

FROM ubuntu
COPY "run.sh" .
RUN ["chmod", "+x", "./run.sh"]
ENTRYPOINT [ "./run.sh" ]

这将允许 ./run.sh 在容器旋转时运行:

This will allow ./run.sh to run when the container is spun:

$ docker build -t test .
Step 1/4 : FROM ubuntu
 ---> 4e2eef94cd6b
Step 2/4 : COPY "run.sh" .
 ---> 37225979730d
Step 3/4 : RUN ["chmod", "+x", "./run.sh"]
 ---> Running in 5f20ded00739
Removing intermediate container 5f20ded00739
 ---> 41174edb932c
Step 4/4 : ENTRYPOINT [ "./run.sh" ]
 ---> Running in bed7717c1242
Removing intermediate container bed7717c1242
 ---> 554da7be7972
Successfully built 554da7be7972
Successfully tagged test:latest

$ docker run -it test
Input something!
Test message
You wrote Test message!

这篇关于添加交互式用户输入,例如 Docker 容器中的“读取"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 01:19