509

I use docker logs [container-name] to see the logs of a specific container.

Is there an elegant way to clear these logs?

Promise Preston
  • 24,334
  • 12
  • 145
  • 143
Youssouf Maiga
  • 6,701
  • 7
  • 26
  • 42
  • 44
    On a sidenote, you can get the size of the logs via `sudo sh -c "du -ch /var/lib/docker/containers/*/*-json.log"` – Daniel F May 25 '18 at 13:03
  • 2
    Not exactly clearing the logs, but to avoid seeing the old logs you can use "-n" and the "-f" option. -n: Number of lines to show from the end of the logs (default "all") -f: Follow log output $ docker logs -n 0 -f [container-name] This will show you incoming logs only – jna May 28 '21 at 13:07
  • If you tried all the answers but `docker logs foo` is still showing several lines, try this https://stackoverflow.com/a/76377582/3957754 – JRichardsz May 31 '23 at 22:09

24 Answers24

672

First the bad answer. From this question there's a one-liner that you can run:

echo "" > $(docker inspect --format='{{.LogPath}}' <container_name_or_id>)

instead of echo, there's the simpler:

: > $(docker inspect --format='{{.LogPath}}' <container_name_or_id>)

or there's the truncate command:

truncate -s 0 $(docker inspect --format='{{.LogPath}}' <container_name_or_id>)

I'm not a big fan of either of those since they modify Docker's files directly. The external log deletion could happen while docker is writing json formatted data to the file, resulting in a partial line, and breaking the ability to read any logs from the docker logs cli. For an example of that happening, see this comment on duketwo's answer:

after emptying the logfile, I get this error: error from daemon in stream: Error grabbing logs: invalid character '\x00' looking for beginning of value

Instead, you can have Docker automatically rotate the logs for you. This is done with additional flags to dockerd if you are using the default JSON logging driver:

dockerd ... --log-opt max-size=10m --log-opt max-file=3

You can also set this as part of your daemon.json file instead of modifying your startup scripts:

{
  "log-driver": "json-file",
  "log-opts": {"max-size": "10m", "max-file": "3"}
}

These options need to be configured with root access. Make sure to run a systemctl reload docker after changing this file to have the settings applied. This setting will then be the default for any newly created containers. Note, existing containers need to be deleted and recreated to receive the new log limits.


Similar log options can be passed to individual containers to override these defaults, allowing you to save more or fewer logs on individual containers. From docker run this looks like:

docker run --log-driver json-file --log-opt max-size=10m --log-opt max-file=3 ...

or in a compose file:

version: '3.7'
services:
  app:
    image: ...
    logging:
      options:
        max-size: "10m"
        max-file: "3"

For additional space savings, you can switch from the json log driver to the "local" log driver. It takes the same max-size and max-file options, but instead of storing in json it uses a binary syntax that is faster and smaller. This allows you to store more logs in the same sized file. The daemon.json entry for that looks like:

{
  "log-driver": "local",
  "log-opts": {"max-size": "10m", "max-file": "3"}
}

The downside of the local driver is external log parsers/forwarders that depended on direct access to the json logs will no longer work. So if you use a tool like filebeat to send to Elastic, or Splunk's universal forwarder, I'd avoid the "local" driver.

I've got a bit more on this in my Tips and Tricks presentation.

BMitch
  • 231,797
  • 42
  • 475
  • 450
  • 13
    I did a `service docker restart` which on its own did not work. Also had to brand create new containers before it took effect. i.e. just bringing up the old containers did not apply the new logging – Robbo_UK Jul 25 '18 at 09:10
  • 5
    I am using Docker 1.13.1, and the 'docker inspect --format='{{.LogPath}}' ' returns a null string ("")....but I am still getting output from 'docker logs '?!? Where is that coming from and how do I clear it?? – JD Allen Feb 20 '19 at 00:45
  • @JDAllen 1.13.1 is long out of support. I don't have a system that old to view their inspect output. – BMitch Mar 27 '19 at 18:39
  • Better yet would be `echo -n > ...`. Anyway, I would like to be able to have more control over my logs. For instance, after *docker-compose* restart, I would love to have the mechanism to do something with the preserved logs. – NarūnasK Aug 27 '19 at 20:04
  • @NarūnasK It's an open source project, you can submit a PR. Probably easier to write a wrapper around your calls to `docker-compose` – BMitch Aug 27 '19 at 20:35
  • I had a "permission denied" warning on running the top code. – darksoulsong Sep 27 '19 at 12:05
  • @darksoulsong All of these changes require root access. – BMitch Sep 27 '19 at 13:41
  • One way to use the `echo "" >...` safely, though, is to stop docker first. Run that `echo` command, then restart docker. I suppose that stopping docker may not be an option to some, of course. Also you need to ask docker for the filename before you stop it and run the echo as root or use `sudo truncate -s 9 ` as shown by others. – Alexis Wilke Oct 26 '19 at 23:15
  • 2
    @AlexisWilke if you're able to stop docker, then you're likely able to stop your container. If you can do the latter, then recreating the container with the logging options would be my advice. The new container has no old logs, and new logs will be rolled automatically, solving both the short term and long term issue at the same time. – BMitch Oct 27 '19 at 02:32
  • This doesn't work if the container is so old it has rotated the logs. Only the 2nd answer will fix that but will wipe all container logs and not only 1 – Freedo Jan 02 '20 at 21:41
  • use `>` instead of `echo "" >` works fines – a55 Dec 08 '20 at 18:49
  • Worked running as `sudo su` – bonafernando Dec 17 '20 at 19:54
  • 1
    If this is not a production environment, then I'd say it would be safe to simply stop the container, truncate the log, and start the container again. – Vitaliy Mar 18 '21 at 09:53
  • 1
    @Vitaliy reiterating my comment above, if you can stop the container, you should also be able to recreate the container with options to automatically rotate the logs. – BMitch Mar 18 '21 at 11:57
  • 1
    @BMitch, this is not what I always want - many times in a test environment I want the log to collect as much information as possible, and only once in a while to reset it. – Vitaliy Mar 18 '21 at 18:26
  • The commands worked great. For some reason log rotation wasn't working for one of the DockerEE system containers, so had to use the commands to check the log size and truncate. – cnu Aug 10 '21 at 15:28
  • a one-liner, why not: docker ps|awk {'print $1'}|xargs docker inspect --format='{{.LogPath}}' |xargs truncate -s 0 | because u can add "|grep" between in case u only want to purge specific containers... – michabbb Oct 29 '21 at 16:19
  • The problem is that in all likelihood the user will be trying to clear the logs so that they can identify relevant output; rotating logs does not address this issue at all (a smaller log with 3000 lines is just as useless as one with 30000), unless a method to force the rotation manually is provided... – Peter Kionga-Kamau Dec 13 '22 at 21:47
  • 1
    @PeterKionga-Kamau this is solving the problem that logs take disk space and grow unconstrained with long running containers. To view logs after a specific time, use `--since`. – BMitch Dec 13 '22 at 21:52
  • @BMitch Nice! So for logs starting at the time of the command, `docker logs [container_name] --follow --since 0m` – Peter Kionga-Kamau Dec 14 '22 at 00:52
  • It's weird why docker itself doesn't have such e feature. – Parsa Noori Feb 07 '23 at 08:50
  • @bmitch should is developer tongue for "i have no proof and problems will be yours if you try", right? – Florian Heigl Jun 06 '23 at 23:58
  • @FlorianHeigl I'm not sure what you're asking about. There's a lot to the above answer and quite a few comments here. Please quote what you're referencing. – BMitch Jun 07 '23 at 01:42
458

Use:

truncate -s 0 /var/lib/docker/containers/**/*-json.log

You may need sudo

sudo sh -c "truncate -s 0 /var/lib/docker/containers/**/*-json.log"

ref. Jeff S. Docker: How to clear the logs properly for a Docker container?

Reference: Truncating a file while it's being used (Linux)

Andrew Theken
  • 3,392
  • 1
  • 31
  • 54
duketwo
  • 4,865
  • 1
  • 11
  • 9
  • 5
    truncate: cannot open ‘/var/lib/docker/containers/*/*-json.log’ for writing: No such file or directory – BTR Naidu Aug 11 '17 at 14:53
  • 2
    @BTRNaidu you have to run it as root/sudo, the content of `containers` is not available otherwise. – spydon Dec 05 '17 at 10:15
  • 50
    ```sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"``` - worked for me – Jeff S. Apr 02 '18 at 23:47
  • You'd have to sudo that as well, that's when the antennas should go out and detect the danger. – lucid_dreamer Jun 22 '18 at 23:20
  • 8
    Ignore the two professionals above. If you are unsure, you can just check with "ls /var/lib/docker/containers/*/*-json.log" what is being truncated. – duketwo Jul 01 '18 at 05:27
  • If you happen to do it within a container, then /var/lib/docker is mounted to the container somehow. Be very careful: https://github.com/moby/moby/issues/22260#issuecomment-263035087 – aGuegu Apr 28 '19 at 17:35
  • 1
    after emptying the logfile, I get this error: `error from daemon in stream: Error grabbing logs: invalid character '\x00' looking for beginning of value` – arcol May 08 '19 at 07:10
  • 1
    @BTRNaidu @JeffShillitto @duketwo `sudo sh -c "[command with globs]"` works because that expands the globs *inside* a root shell, rather than as the user running the `sudo` command. If you don't have access to even list the files inside /var/lib/docker/containers/ a glob inside it is just going to expand to itself (unless you `shopt -s nullglob`). – l0b0 Jun 05 '19 at 20:37
  • 1
    You need to add `*` after .log to clear logs that have already been rotated but still show up with `docker logs` – Freedo Apr 04 '20 at 15:00
  • are you sure that it won't delete files inside containers matching the pattern? – Pavel Niedoba May 22 '23 at 21:58
100

On Docker for Windows and Mac, and probably others too, it is possible to use the tail option. For example:

docker logs -f --tail 100

This way, only the last 100 lines are shown, and you don't have first to scroll through 1M lines...

(And thus, deleting the log is probably unnecessary)

Egbert Nierop
  • 2,066
  • 1
  • 14
  • 16
  • 113
    The idea is to clean log files and not to print the last n lines of log files – Youssouf Maiga Mar 29 '19 at 13:36
  • 1
    some edited my post but the suggestion does not work, at least not on docker 20.10.5 to use docker logs -f --since 30s (e.g.) – Egbert Nierop Jul 08 '21 at 09:14
  • 4
    if you are only wanting logs from a particular container using docker-compose, you can also use this command: `docker-compose logs --tail 10 --follow service1 service2 etc` – Kip Nov 12 '21 at 15:04
  • 3
    Downvoted because it does not even attempt to answer the original question – Aquarelle Sep 09 '22 at 00:20
  • I found this question looking for a way to stop docker-compose logs -f from endlessly scrolling before reaching the tail. This solution works perfectly for that. – Mike McCartin Feb 09 '23 at 16:31
65
sudo sh -c "truncate -s 0 /var/lib/docker/containers/*/*-json.log"
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
richard
  • 1,845
  • 1
  • 20
  • 30
  • 11
    To get the size of the logs `sudo sh -c "du -ch /var/lib/docker/containers/*/*-json.log"`, to only get the total of the size of the logs `sudo sh -c "du -ch /var/lib/docker/containers/*/*-json.log | grep total"` – Daniel F May 25 '18 at 13:00
  • Are there any issues with dockerd/aufs being ignorant of and incapable to remove the rotated log files? – ThorSummoner Aug 06 '18 at 19:43
  • This command worked for me whereas the other commands in this SO have not. If it matters, I'm running Docker version 18 on CentOS 7 – Tundra Fizz May 04 '19 at 00:51
40

You can set up logrotate to clear the logs periodically.

Example file in /etc/logrotate.d/docker-logs

/var/lib/docker/containers/*/*.log {
 rotate 7
 daily
 compress
 size=50M
 missingok
 delaycompress
 copytruncate
}
AlexPnt
  • 579
  • 5
  • 9
  • 1
    and how do i use this? it is used as default with `docker run`? file `/etc/logrotate.d/docker-logs` does not exists, i have to create it? – Carlos.V Apr 12 '19 at 19:03
  • 1
    You have to call the logrotate utility (logrotate ) and it will read your configuration and run the cleanup. You can also set it as a cron job for example. – AlexPnt Apr 15 '19 at 10:21
  • 3
    The problem with this one is that it may not be properly synchronized with what docker is doing. Using the docker facility is probably much wiser. (the `"log-opts"` as shown by BMitch) – Alexis Wilke Oct 27 '19 at 10:14
  • 3
    `logrotate` might already be set up. On my Ubuntu 20.04 server it’s set as a cron job: `cat /etc/cron.daily/logrotate`. Try `sudo logrotate -d /etc/logrotate.conf` to do a dry run to see if the newly created `/etc/logrotate.d/docker-logs` does what it should do. – Harm Dec 16 '20 at 17:44
34

You can also supply the log-opts parameters on the docker run command line, like this:

docker run --log-opt max-size=10m --log-opt max-file=5 my-app:latest

or in a docker-compose.yml like this

my-app:
image: my-app:latest
logging:
    driver: "json-file"
    options:
        max-size: "10m"
        max-file: "5"

Credits: https://medium.com/@Quigley_Ja/rotating-docker-logs-keeping-your-overlay-folder-small-40cfa2155412 (James Quigley)

DangerPaws
  • 765
  • 1
  • 7
  • 21
Dag Baardsen
  • 774
  • 7
  • 9
  • 1
    The parameter values should be quoted (i.e. `"5"` and `"10m"`respectively), as shown [here](https://success.docker.com/article/how-to-setup-log-rotation-post-installation) for the global daemon.json file, but it is the same for a docker-compose.yml. In both cases, it will only affect newly created containers. – Adrian W Apr 04 '20 at 16:27
  • 1
    @AdrianW: docker-compose.yml do not need quotes. These are entirely different file formats. And yes, you're right: "docker run" commands and docker-compose parameters do only affect newly created containers - as opposed to the answer here with the most votes which affects only restarted dockerd daemons and is available through root access only. My answer is supposed to show a much simpler and updated path than editing than restarting the entire dockerd process. – Dag Baardsen Apr 05 '20 at 17:22
  • Without quotes, I get: _ERROR: for app Cannot create container for service app: json: cannot unmarshal number into Go struct field LogConfig.Config of type string_ If I quote like this: `"5"` it works. The `10m` work without quoting indeed. – Adrian W Apr 05 '20 at 19:47
  • Looks like there is a difference between Docker for Windows and Docker for Linux. On the latter, I have to enclose the values in quotes. Not on the former. Updated the description to fit both. Thanks, @AdrianW – Dag Baardsen Apr 06 '20 at 18:00
20

Docker4Mac, a 2018 solution:

LOGPATH=$(docker inspect --format='{{.LogPath}}' <container_name_or_id>)
docker run -it --rm --privileged --pid=host alpine:latest nsenter -t 1 -m -u -n -i -- truncate -s0 $LOGPATH

The first line gets the log file path, similar to the accepted answer.

The second line uses nsenter that allows you to run commands in the xhyve VM that servers as the host for all the docker containers under Docker4Mac. The command we run is the familiar truncate -s0 $LOGPATH from non-Mac answers.

If you're using docker-compose, the first line becomes:

local LOGPATH=$(docker inspect --format='{{.LogPath}}' $(docker-compose ps -q <service>))

and <service> is the service name from your docker-compose.yml file.

Thanks to https://github.com/justincormack/nsenter1 for the nsenter trick.

elifiner
  • 7,347
  • 8
  • 39
  • 48
  • 7
    And to truncate the logs of all containers you can use a shell wildcard as shown in other answers, so it's just one command: `docker run -it --rm --privileged --pid=host alpine:latest nsenter -t 1 -m -u -n -i -- sh -c 'truncate -s0 /var/lib/docker/containers/*/*-json.log'` – bradenm Sep 05 '18 at 22:22
11

You can't do this directly through a Docker command.

You can either limit the log's size, or use a script to delete logs related to a container. You can find scripts examples here (read from the bottom): Feature: Ability to clear log history #1083

Check out the logging section of the docker-compose file reference, where you can specify options (such as log rotation and log size limit) for some logging drivers.

Alpha
  • 7,586
  • 8
  • 59
  • 92
Tristan
  • 8,733
  • 7
  • 48
  • 96
11

Here is a cross platform solution to clearing docker container logs:

docker run --rm -v /var/lib/docker:/var/lib/docker alpine sh -c "echo '' > $(docker inspect --format='{{.LogPath}}' CONTAINER_NAME)"

Paste this into your terminal and change CONTAINER_NAME to desired container name or id.

Max Barrass
  • 2,776
  • 1
  • 19
  • 10
  • for me this is the only working solution to delete logs when using wsl2 on windows. However it may be caused some configuration problem - theoretically access to docker logs should be available from wsl2 distro (for example ubuntu) however this is not working for me. – Nicramus Dec 15 '20 at 07:11
  • @Nicramus I have trouble with the `-v` option under windows: `docker: Error response from daemon: mkdir C:\Program Files\Git\var: Access is denied.` – Daniel Alder Mar 16 '21 at 16:43
  • 1
    Don't use Git-for-Windows bash(MingW) as it mounts the git installation folder as a virtual root of file system tree. Try Ubuntu for Windows and run docker in that. Or, use Docker for Windows and find out where these log files are located and delete them. – WesternGun May 26 '21 at 13:08
  • 1
    Worked great on a Linux machine. Thanks! – Jonathan Hult Sep 10 '21 at 19:27
  • 1
    Just use powershell 7 core. Please please, pretty please stop using any of the MING/CYGWIN shells they just causing you issues on windows, unless you know why you need them. If you just need them for LINUX commands just add C:\Program Files\Git\usr\bin to your path and you will have all the commands you need. – Max Barrass Mar 03 '22 at 12:18
9

As a root user, try to run the following:

>  /var/lib/docker/containers/*/*-json.log

or

cat /dev/null > /var/lib/docker/containers/*/*-json.log

or

echo "" > /var/lib/docker/containers/*/*-json.log
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mati kepa
  • 2,543
  • 19
  • 24
8

On my Ubuntu servers even as sudo I would get Cannot open ‘/var/lib/docker/containers/*/*-json.log’ for writing: No such file or directory

But combing the docker inspect and truncate answers worked :

sudo truncate -s 0 `docker inspect --format='{{.LogPath}}' <container>`
aqwan
  • 470
  • 4
  • 6
8

I do prefer this one (from solutions above):

truncate -s 0 /var/lib/docker/containers/*/*-json.log

However I'm running several systems (Ubuntu 18.x Bionic for example), where this path does not work as expected. Docker is installed through Snap, so the path to containers is more like:

truncate -s 0 /var/snap/docker/common/var-lib-docker/containers/*/*-json.log
igraczech
  • 2,408
  • 3
  • 25
  • 30
7

This will delete all logfiles for all containers:

sudo find /var/lib/docker/containers/ -type f -name "*.log" -delete
james-see
  • 12,210
  • 6
  • 40
  • 47
Jakobovski
  • 3,203
  • 1
  • 31
  • 38
  • 8
    The community encourages adding explanations alongisde code, rather than purely code-based answers (see [here](https://meta.stackoverflow.com/questions/300837/what-comment-should-i-add-to-code-only-answers)). – costaparas Jan 25 '21 at 14:03
  • 2
    That won't work as expected. As running container would have file still opened and would continue to write to it. It just won't be visible in directory, but would take disk space. (see linux unlink ) – Bogdan Mart Jul 06 '22 at 16:21
5

Not sure if this is helpful for you, but removing the container always helps.

So, if you use docker-compose for your setup, you can simply use docker-compose down && docker-compose up -d instead of docker-compose restart. With a proper setup (make sure to use volume mounts for persistent data), you don't lose any data this way.

Sure, this is more than the OP requested. But there are various situations where the other answers cannot help (if using a remote docker server or working on a Windows machine, accessing the underlying filesystem is proprietary and difficult)

Daniel Alder
  • 5,031
  • 2
  • 45
  • 55
  • Worked for me. Was helpful because I do have several containers, volumes, docker-compose.yml, etc and this did it "smoothly". I always forget to add the `-d` flag (detatched) when running the up command, so don't forget to do it :) – DarkCygnus Dec 20 '21 at 22:34
5

Thanks to answer by @BMitch, I've just wrote a shell script to clean logs of all the containers:

#!/bin/bash
ids=$(docker ps -a --format='{{.ID}}')
for id in $ids
do
        echo $(docker ps -a --format='{{.ID}} ### {{.Names}} ### {{.Image}}' | fgrep $id)
        truncate -s 0 $(docker inspect --format='{{.LogPath}}' $id)
        ls -llh $(docker inspect --format='{{.LogPath}}' $id)
done
Muhammad Tariq
  • 3,318
  • 5
  • 38
  • 42
Mohsen Abasi
  • 2,050
  • 28
  • 30
4

Linux/Ubuntu:

If you have several containers and you want to remove just one log but not others.

  • (If you have issues like "Permission denied" do first sudo su.)
  • List all containers: docker ps -a
  • Look for the container you desire and copy the CONTAINER ID. Example: E1X2A3M4P5L6.
  • Containers folders and real names are longer than E1X2A3M4P5L6 but first 12 characters are those resulted in docker ps -a.
  • Remove just that log: > /var/lib/docker/containers/E1X2A3M4P5L6*/E1X2A3M4P5L6*-json.log (Replace E1X2A3M4P5L6 for your result !! )

As you can see, inside /containers are the containers, and logs has the same name but with -json.log at the end. You just need to know that first 12 characters, because * means "anything".

Emeeus
  • 5,072
  • 2
  • 25
  • 37
4

Sharing this since the other answers seem overly complex.

The easiest way to scrap associate container logs will be to force recreate it.

docker-compose up -d [container] --force-recreate

Then running docker-compose logs [container] should result in only new entries since the container came up.

Verron Knowles
  • 883
  • 8
  • 9
3

I needed something I could run as one command, instead of having to write docker ps and copying over each Container ID and running the command multiple times. I've adapted BMitch's answer and thought I'd share in case someone else may find this useful.

Mixing xargs seems to pull off what I need here:

docker ps --format='{{.ID}}' | \
  xargs -I {} sh -c 'echo > $(docker inspect --format="{{.LogPath}}" {})'

This grabs each Container ID listed by docker ps (will erase your logs for any container on that list!), pipes it into xargs and then echoes a blank string to replace the log path of the container.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Reece
  • 574
  • 3
  • 10
2

Docker for Mac users, here is the solution:

    1. Find log file path by:

      $ docker inspect | grep log

    1. SSH into the docker machine( suppose the name is default, if not, run docker-machine ls to find out):

      $ docker-machine ssh default

    1. Change to root user(reference):

      $ sudo -i

    1. Delete the log file content:

      $ echo "" > log_file_path_from_step1

Jinsong Li
  • 6,347
  • 1
  • 23
  • 20
  • 4
    docker-machine does not work with Docker for Mac. You can instead run "docker run -ti -v /var/lib/docker/containers:/var/inception centos bash" then "truncate --size 0 /var/inception/08d29a7d469232cfef4456dc6eebcbf313bf01ba73e479520a036150c5ab84de/08d29a7d469232cfef4456dc6eebcbf313bf01ba73e479520a036150c5ab84de-json.log" – jamshid Jun 27 '18 at 05:04
  • You may use `docker exec -it default sh` to enter an sh shell in a container. However, many containers do not implicitly make the `sudo` command available. – Dag Baardsen Apr 05 '20 at 17:30
2

To remove/clear docker container logs we can use below command

$(docker inspect container_id|grep "LogPath"|cut -d """ -f4) or $(docker inspect container_name|grep "LogPath"|cut -d """ -f4)

2

If you need to store a backup of the log files before deleting them, I have created a script that performs the following actions (you have to run it with sudo) for a specified container:

  1. Creates a folder to store compressed log files as backup.
  2. Looks for the running container's id (specified by the container's name).
  3. Copy the container's log file to a new location (folder in step 1) using a random name.
  4. Compress the previous log file (to save space).
  5. Truncates the container's log file by certain size that you can define.

Notes:

  • It uses the shuf command. Make sure your linux distribution has it or change it to another bash-supported random generator.
  • Before use, change the variable CONTAINER_NAME to match your running container; it can be a partial name (doesn't have to be the exact matching name).
  • By default it truncates the log file to 10M (10 megabytes), but you can change this size by modifying the variable SIZE_TO_TRUNCATE.
  • It creates a folder in the path: /opt/your-container-name/logs, if you want to store the compressed logs somewhere else, just change the variable LOG_FOLDER.
  • Run some tests before running it in production.
#!/bin/bash
set -ex

############################# Main Variables Definition:
CONTAINER_NAME="your-container-name"
SIZE_TO_TRUNCATE="10M"

############################# Other Variables Definition:
CURRENT_DATE=$(date "+%d-%b-%Y-%H-%M-%S")
RANDOM_VALUE=$(shuf -i 1-1000000 -n 1)
LOG_FOLDER="/opt/${CONTAINER_NAME}/logs"
CN=$(docker ps --no-trunc -f name=${CONTAINER_NAME} | awk '{print $1}' | tail -n +2)
LOG_DOCKER_FILE="$(docker inspect --format='{{.LogPath}}' ${CN})"
LOG_FILE_NAME="${CURRENT_DATE}-${RANDOM_VALUE}"

############################# Procedure:
mkdir -p "${LOG_FOLDER}"
cp ${LOG_DOCKER_FILE} "${LOG_FOLDER}/${LOG_FILE_NAME}.log"
cd ${LOG_FOLDER}
tar -cvzf "${LOG_FILE_NAME}.tar.gz" "${LOG_FILE_NAME}.log"
rm -rf "${LOG_FILE_NAME}.log"
truncate -s ${SIZE_TO_TRUNCATE} ${LOG_DOCKER_FILE}

You can create a cronjob to run the previous script every month. First run:

sudo crontab -e

Type a in your keyboard to enter edit mode. Then add the following line:

0 0 1 * * /your-script-path/script.sh

Hit the escape key to exit Edit mode. Save the file by typing :wq and hitting enter. Make sure the script.sh file has execution permissions.

Edenshaw
  • 1,692
  • 18
  • 27
1

On computers with docker desktop we use: truncate -s 0 //wsl.localhost/docker-desktop-data/data/docker/containers/*/*-json.log

For linux distributions you can use this it works for me with this path: truncate -s 0 /var/lib/docker/containers/*/*-json.log

0

If your host machine uses systemd, consider using journald logging driver.

This way you receive centralized log management, instead of silently logging to local un-rotated file (default json-file logging driver does exactly this way). In my case, using docker defaults led to diskspace exhausting (logfile eated over 7G).

Journald daemon can easily be configured to rotate logs, see the docs

Eugene
  • 2,336
  • 21
  • 28
-12

docker system prune
run this command in command prompt

ScottC
  • 3,941
  • 1
  • 6
  • 20