gpt4 book ai didi

linux - 在docker中重定向命令输出

转载 作者:IT老高 更新时间:2023-10-28 12:36:48 30 4
gpt4 key购买 nike

我想为我的服务器做一些简单的日志记录,这是一个在 Docker 容器中运行的小型 Flask 应用程序。

这里是 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 重定向到一个文件。现在我在其中运行这个容器和外壳

docker run -d -p 80:80 perfektimprezy
docker exec -it "... id of container ..." bash

并注意以下事项:

服务器正在运行,网站正在运行

没有/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 到容器,我可以在控制台中看到应用程序生成输出。

使用 Docker 时如何正确地将 stdout/err 重定向到文件?

最佳答案

当您在 Dockerfile 中将 JSON 列表指定为 CMD 时,它不会在 shell 中执行,因此通常的 shell 函数,如 stdout 和 stderr 重定向,不会工作。

来自 documentation :

The exec form is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes (').

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 脚本的命令行参数.

改用以下方法之一(两者都应该工作):

  1. CMD "python index.py > server.log 2>&1"
  2. CMD ["/bin/sh", "-c", "python index.py > server.log 2>&1"]

关于linux - 在docker中重定向命令输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34632959/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com