简体   繁体   English

从Docker中运行的进程返回日志文件

[英]Returning log file from process run in docker

I'm a total newbie to docker, and am having trouble on how to approach this problem. 我是docker的新手,在解决该问题时遇到了麻烦。 Consider this super simplified cli tool that produces a log when ran with docker run . 考虑使用这个超级简化的cli工具,该工具在使用docker run时会生成日志。

import click
import logging

logging.basicConfig(filename='log.log')
logger = logging.getLogger(__name__)

@click.group()
@click.version_option('1.0')
def cli():
    '''docker_cli with docker test'''


@cli.command('run')
@click.argument('name', default='my name')
def run(name):
    logger.info("running 'run' within docker")
    print('Hello {}'.format(name))

And my dockerfile is as follows: 我的dockerfile如下:

FROM python:3.5-slim

LABEL maintainer="Boudewijn Aasman"
LABEL version="1.0"

ENV config production

RUN mkdir /docker_cli
COPY docker_cli ./docker_cli
COPY setup.py .

RUN python setup.py install

CMD ["cli", "run"]

If I execute the container using: 如果我使用以下命令执行容器:

docker run cli_test cli run world

how do I retrieve the log file that gets created during the process? 如何检索在此过程中创建的日志文件? The container exits immediately after the command print out 'Hello world'. 命令打印出“ Hello world”后,容器立即退出。 My assumption is using a volume, but not sure how to make it work. 我的假设是使用体积,但不确定如何使它起作用。

Have you tried this? 你有尝试过吗?

docker logs cli_test

EDIT: Sorry, I missed this the first time, but in order for this to work, you'll have to log to STDERR, not to a log file. 编辑:对不起,我第一次错过了这个,但是为了使其正常工作,您必须登录到STDERR,而不是日志文件。 (Thanks @Gonzalo Matheu for pointing this out.) To get it working, it should be as simple as making this small additional change: (感谢@Gonzalo Matheu指出这一点。)要使其正常运行,它应该与进行此小的附加更改一样简单:

logging.basicConfig()  # note no file name

You can either share a local directory: 您可以共享本地目录:

docker run -v full-path-your-local-dir:. cli_test cli run world

Or create a docker volume 或创建一个Docker卷

docker volume create cli_test_volume
docker run -v cli-test_volume:. cli_test cli run world
docker volume inspect cli_test_volume # will show where the volume is located.

For both of these approaches you will need to write the logs in a different path than the application . 对于这两种方法,您都需要在与应用程序不同的路径中写入日志 Otherwise, app code will be overwritten by the shared volume. 否则,应用程序代码将被共享卷覆盖。

There is another alternative, which is to copy files from the container using create and cp : 还有另一种选择,就是使用createcp从容器中复制文件:

docker create --name cli_test_instance cli_test run world
docker start  cli_test_instance 
docker cp cli_test_instance:log.log .

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

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