在通常的Linux伺服器中,有一些服務本身沒有日誌,只能通過 tail -f /var/log/messages來檢視其執行日誌,比如nrpe server。但是,如果想在docker容器中實現這個功能就需要費點事了。具體步驟如下:
1、安裝rsyslog
# yum -y install rsyslog
2、啟動syslog服務
# rsyslogd
3、測試是否在messages中生成日誌
# logger "Hello World"
結果發現,在messages中只有一下一行:"Aug 1 11:31:37 f2570fed2149 rsyslogd: [origin software="rsyslogd" swVersion="7.4.7" x-pid="73" x-info="http://www.rsyslog.com"] start",故可認定其未工作。原因是:“The problem was that in RHEL7 and Fedora we now use journald, which listens on /dev/log for incoming messages. In RHEL7 and Fedora, rsyslog actually reads messages from the journal via its API by default.But not all docker containers run systemd and journald. (Most don’t). In order to get the rsyslogd to work the way the user wanted, he would have to modify the configuration file, /etc/rsyslog.conf”。
解決辦法如下:
1、修改syslog配置—— # vi /etc/rsyslog.conf
1、註釋掉 $ModLoad imjournal 2、設定 $OmitLocalLogging 為 off 3、註釋掉 $IMJournalStateFile imjournal.state
2、提交容器至映象,重新建立容器
[root@localhost home]# docker commit f2570fed2149 centos_with_syslog:v1.0 830e298b4c103f70154ec9c8ceae44ec4602ed22063dae8e13a3f9aff4c3260a [root@localhost home]# docker run -d -p 223:222 -v /dev/log:/dev/log -ti centos_with_syslog:v1.0 /run.sh dc2eb83e80ced6f553eb1dd7032489d37b4d934a9126f61dfbd4d6a2243e98f1
3、測試驗證
[root@localhost home]# docker exec -ti dc2eb83e80ced6f553eb1dd7032489d37b4d934a9126f61dfbd4d6a2243e98f1 /bin/bash [root@dc2eb83e80ce /]# logger "hello everyone" [root@dc2eb83e80ce /]# exit exit [root@localhost home]# tail -f /var/log/messages (注意實在宿主機上的messages檔案中檢視日誌) Aug 1 19:57:51 localhost docker: time="2015-08-01T19:57:51+08:00" level=info msg="-job log(exec_start: /bin/bash , dc2eb83e80ced6f553eb1dd7032489d37b4d934a9126f61dfbd4d6a2243e98f1, centos_with_syslog:v1.0) = OK (0)" Aug 1 19:57:51 localhost docker: time="2015-08-01T19:57:51+08:00" level=info msg="POST /v1.18/exec/9ae97d0666bf5abcd8d95eb87d10c5d013a0f006c2cb1adc7ff8f7baaacf14fc/resize?h=37&w=191" Aug 1 19:57:51 localhost docker: time="2015-08-01T19:57:51+08:00" level=info msg="+job execResize(9ae97d0666bf5abcd8d95eb87d10c5d013a0f006c2cb1adc7ff8f7baaacf14fc, 37, 191)" Aug 1 19:57:51 localhost docker: time="2015-08-01T19:57:51+08:00" level=info msg="-job execResize(9ae97d0666bf5abcd8d95eb87d10c5d013a0f006c2cb1adc7ff8f7baaacf14fc, 37, 191) = OK (0)" Aug 1 19:58:09 localhost logger: hello everyone