Docker 容器将日志保存在主机目录 [英] Docker container save logs on the host directory
问题描述
我有一个类似于这个的问题.运行我的 docker-compose.yml
文件时,我会自动创建一个 docker 映像,并按照我的 dockerfile
中的规定运行某些应用程序.这些应用程序会生成一些日志,但这些日志被写入在 docker 容器内,在 /home/logs/
文件夹中.
I have a question similar to this one. When run my docker-compose.yml
file, I automatically create a docker image and as specified in my dockerfile
, I run certain apps. These apps produce some logs, but these logs are written inside the docker container, in /home/logs/
folder.
我如何指明这些日志写在容器的外部,写在我的/path/on/host
地址上?仅仅是因为如果容器发生故障,我需要查看日志而不是丢失它们!
How can I indicate that these logs be writted outside the container, on my /path/on/host
address? Simply because if the container was failed, I need to see the logs and not lose them!
这是我的docker-compose.yml
:
version: '3'
services:
myapp:
build: .
image: myapp
ports:
- "9001:9001"
这是我的dockerfile
:
FROM java:latest
COPY myapp-1.0.jar /home
CMD java -jar /home/myapp-1.0.jar
我只是在生产机器上使用 docker-compose up -d
运行它.
And I simply run it on production machine with docker-compose up -d
.
(顺便说一句,我是 docker 新手.我所有的步骤都正确吗?我遗漏了什么吗?!我看到一切都很好,但我的应用程序正在运行!)
(BTW, I'm new to dockers. Are all of my steps correct? Am I missing anything?! I see all is fine and myapp is running though!)
推荐答案
您只需要一个 docker 卷即可保存日志文件.因此,在与 docker-compose.yml 相同的目录中创建一个日志目录,然后定义一个卷挂载.定义挂载时,请记住语法是
.
All you need is a docker volume in order to persist the log files. So in the same directory as your docker-compose.yml create a logs directory, then define a volume mount. When defining a mount remember the syntax is <host_machine_directy>:<container_directory>
.
试试下面的卷,让我知道你得到了什么.
Give the following volume a try and let me know what you get back.
version: '3'
services:
myapp:
build: .
image: myapp
ports:
- "9001:9001"
volumes:
- ./logs:/home/logs
另外值得注意的是,持久性与这种方法是双向的.从容器内对文件所做的任何更改都会反映回主机.来自主机的任何更改也会反映在容器内.
Also worth noting that persistence goes both ways with this approach. Any changes made to the files from within the container are reflected back onto the host. Any changes from the host, are also reflected inside the container.
这篇关于Docker 容器将日志保存在主机目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!