uni farm

dockerコンテナのlogをAmazon CloudWatch Logsに保存する

EC2上で動いているdockerコンテナのログを Amazon CloudWatch Logsに保存する手順を書いておく

環境

docker: 17.09.0-ce docker-compose: 1.16.1

EC2にポリシーをアタッチ

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

のポリシーを作成して、EC2のIAM roleにアタッチする

dockerコンテナの実行

awslogs logging driverを使う

docker-compose.yml
version: '3'
services:
  echo:
    image: centos:6.7
    entrypoint: echo
    command: echo From compose
    logging:
      driver: "awslogs"
      options:
        awslogs-region: "ap-northeast-1"
        awslogs-group: "docker"
        tag: '{{ with split .ImageName ":" }}{{join . "_"}}{{end}}-{{.ID}}' # stream nameの名前 "image名_tag-ID"
        awslogs-create-group: "true" # groupがなければ作成される
docker-compose up -d

logの確認

aws consoleで確認

cloudwatch log

awslogsコマンドで確認

pip install awslogs
awslogs get docker centos_6.7-612fc50e378f --start='2h'

docker centos_6.7-612fc50e378f echo From compose

参考

2022, Built with Gatsby. This site uses Google Analytics.