Docker startup time

How can I speed up: docker run and docker exec commands?

Running command takes 0.02s user time, 0.02s sys time (that would be OK in my case), but around 0.5s real time each (not acceptable).

For example:

$ time sudo docker run --cap-add SYS_ADMIN -i -t --memory=100000k --memory-swap=100000k -d -w /tmp -v /home/asd:/tmp my_image
sudo docker run --cap-add SYS_ADMIN -i -t --memory=100000k  -d -w /tmp -v    0,02s user 0,02s system 6% cpu 0,496 total

Can I somehow speed up process of running container or at least understand why is this time wasted?

my_image is created from ubuntu and the image built takes around 800 MB. But from what I checked it does not matter too much - reducing size image to 200 MB does not change execution time of above command.

The overhead time is most likely being spent creating and removing namespaces. To work out where the time is spent, you can run your container in different ways.

First, eliminate the sudo command. Login as root, sudo -s, and run commands from there.

Next try splitting the run into separate create and start steps. This will let you know if the time is spent creating the container or running it:

$ time docker create --cap-add SYS_ADMIN -itd \
  --memory=100000k --memory-swap=100000k \
  -w /tmp -v /home/asd:/tmp my_image

$ time docker start -ai $(docker ps -ql)

Since you run your container detached, consider whether you can remove the tty allocation, and if you need stdin configured, by removing the -it:

$ time sudo docker run --cap-add SYS_ADMIN -d \
  --memory=100000k --memory-swap=100000k \
  -w /tmp -v /home/asd:/tmp my_image

After that, you can start to look at how much time is added to create each of the namespaces for things like the network and pid by disabling them by setting them to the existing host namespace:

$ time sudo docker run --cap-add SYS_ADMIN -itd \
  --net=host --pid=host --uts=host \
  --memory=100000k --memory-swap=100000k \
  -w /tmp -v /home/asd:/tmp my_image

From docker, you can view the actions being performed with docker events and checking the timestamp on each of the actions.

Lastly, keep in mind that docker is a client/server application, and some of the actual time may be socket/network communication between the client and server.

Following @BMitch’s answer, I would say docker exec isn’t slow at all. It’s mostly setup and cleanup of a container.