简体   繁体   English

将此处文档与Dockerfile中的ENTRYPOINT / CMD一起使用

[英]Use here document with ENTRYPOINT/CMD in Dockerfile

What I want to do 我想做的事

My goal is to end up with a Docker image which - as soon as a container is launched from it - reads input from stdin until it meets EOF. 我的目标是最终得到一个Docker映像,该映像在容器启动后立即从stdin读取输入,直到遇到EOF。 Then, it simply writes back what has been read to stdout. 然后,它仅将已读取的内容写回stdout。

Basically, my idea was this should be possible by using the here document syntax cat << EOF . 基本上,我的想法是应该可以通过使用此处文档的语法cat << EOF来实现这一点。


What I did so far 我到目前为止所做的

So far, I tried different variants with the CMD Dockerfile instruction but had no success until now. 到目前为止,我尝试使用CMD Dockerfile指令尝试不同的变体,但到目前为止没有成功。 From all the images I've created I launched containers with docker run -it myimage to keep the container's stdin attached. 从创建的所有映像中,我使用docker run -it myimage启动了容器,以保持容器的stdin连接。

Variant 1 变体1

 FROM alpine 3.7
 CMD ["cat", "<<", "EOF"]

This leads to the following error: 这导致以下错误:

cat: can't open '<<': No such file or directory
cat: can't open 'EOF': No such file or directory


Variant 2 变体2

 FROM alpine 3.7
 CMD ["cat << EOF"]

Result: 结果:

 container_linux.go:265: starting container process caused "exec: \"cat << EOF\": executable file not found in $PATH"


Variant 3 变体3

 FROM alpine:3.7
 CMD ["sh", "-c", "cat << EOF"]

Result: 结果:

This does nothing but returns immediately. 这什么也不做,只是立即返回。


Variant 4 变体4

 FROM alpine: 3.7
 CMD "cat << EOF"

Result: 结果:

 /bin/sh: cat << EOF: not found


What I expect 我期望什么

I'm searching for a solution that behaves like described above. 我正在寻找一种行为如上所述的解决方案。 The following docker run command works perfectly, but I'd like to define this as the default entry point for my Docker image: 以下docker run命令可完美docker run ,但我想将此定义为Docker映像的默认入口点:

 $ docker run -it alpine cat << EOF
 > Hello Docker
 > EOF
 Hello Docker

That can't work because the shell parses the command line, including the heredoc before it executes it. 这是行不通的,因为外壳程序会在执行命令行之前解析命令行,包括heredoc。

Basically you can just do this: 基本上,您可以这样做:

# Dockerfile
FROM xyz
# cat reads from stdin by default if no filename gets passed to it
CMD 'cat'

Build and run the container: 生成并运行容器:

docker build -t foo .
docker run -ti foo
HelloDocker
HelloDocker

You stop the input with Ctrl + d (That's literally EOF) 您可以使用Ctrl + d停止输入(实际上是EOF)


PS: If you want to use a here-doc, run the above container like this: PS:如果要使用Here-doc,请像这样运行以上容器:

docker run -i foo <<EOF
Hello Docker
EOF

Hello Docker

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM