在 docker 中重定向命令输出 [英] Redirecting command output in docker
问题描述
我想为我的服务器做一些简单的日志记录,这是一个在 Docker 容器中运行的小型 Flask 应用程序.
I want to do some simple logging for my server which is a small Flask app running in a Docker container.
这里是 Dockerfile
Here is the Dockerfile
# Dockerfile
FROM dreen/flask
MAINTAINER dreen
WORKDIR /srv
# Get source
RUN mkdir -p /srv
COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz
RUN tar x -f perfektimprezy.tar.gz
RUN rm perfektimprezy.tar.gz
# Run server
EXPOSE 80
CMD ["python", "index.py", "1>server.log", "2>server.log"]
正如你在最后一行看到的,我将 stderr 和 stdout 重定向到一个文件.现在我运行这个容器和 shell
As you can see on the last line I redirect stderr and stdout to a file. Now I run this container and shell into it
docker run -d -p 80:80 perfektimprezy
docker exec -it "... id of container ..." bash
并注意以下几点:
服务器正在运行,网站正在运行
The server is running and the website working
没有/srv/server.log
ps 辅助 |grep python
产生:
root 1 1.6 3.2 54172 16240 ? Ss 13:43 0:00 python index.py 1>server.log 2>server.log
root 12 1.9 3.3 130388 16740 ? Sl 13:43 0:00 /usr/bin/python index.py 1>server.log 2>server.log
root 32 0.0 0.0 8860 388 ? R+ 13:43 0:00 grep --color=auto python
但是没有日志......但是,如果我 docker attach
到容器,我可以看到应用程序在控制台中生成输出.
But there are no logs... HOWEVER, if I docker attach
to the container I can see the app generating output in the console.
如何在使用 Docker 时正确地将 stdout/err 重定向到文件?
How do I properly redirect stdout/err to a file when using Docker?
推荐答案
当您在 Dockerfile
中将 JSON 列表指定为 CMD
时,它将不会在shell,所以通常的 shell 函数,如 stdout 和 stderr 重定向,将不起作用.
When you specify a JSON list as CMD
in a Dockerfile
, it will not be executed in a shell, so the usual shell functions, like stdout and stderr redirection, won't work.
来自文档:
exec 形式被解析为 JSON 数组,这意味着您必须在单词周围使用双引号 ("
) 而不是单引号 ('
).
The exec form is parsed as a JSON array, which means that you must use double-quotes (
"
) around words not single-quotes ('
).
与 shell 形式不同,exec 形式不调用命令 shell.这意味着不会发生正常的 shell 处理.例如,CMD [ "echo", "$HOME";]
不会对 $HOME
进行变量替换.如果你想要 shell 处理,那么要么使用 shell 形式,要么直接执行 shell,例如: CMD [ "sh", "-c", "echo", "$HOME";]
.
Unlike the shell form, the exec form does not invoke a command shell. This means that normal shell processing does not happen. For example, CMD [ "echo", "$HOME" ]
will not do variable substitution on $HOME
. If you want shell processing then either use the shell form or execute a shell directly, for example: CMD [ "sh", "-c", "echo", "$HOME" ]
.
您的命令实际执行的是执行您的 index.py
脚本并传递字符串 "1>server.log"
和 "2>server.log"
作为该 python 脚本的命令行参数.
What your command actually does is executing your index.py
script and passing the strings "1>server.log"
and "2>server.log"
as command-line arguments into that python script.
改用以下方法之一(两者都应该有效):
Use one of the following instead (both should work):
CMD "python index.py >server.log 2>&1"
CMD [/bin/sh"、-c"、python index.py"server.log 2>&1"]
这篇关于在 docker 中重定向命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!