Saturday 9 May 2020

Docker Exec: Execute a command on a running container

‘docker exec’ is used to execute a command on running container.

For example,
For example, execute the command 'docker run ubuntu sleep 1000', it starts a container with ubuntu image and execute the sleep command.

Go to other terminal and execute the command ‘docker ps’ to see all active containers.
$docker run ubuntu echo "Hello World"
Hello World
$
$docker run ubuntu sleep 5
$
$docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
e73d81bec53a        ubuntu              "sleep 5"                15 seconds ago      Exited (0) 9 seconds ago                        nervous_bhaskara
12bf7981e2c5        ubuntu              "echo 'Hello World'"     31 seconds ago      Exited (0) 29 seconds ago                       competent_pascal

Now use below syntax to execute a command on running container.

docker exec {containerId/containerName} {command}

$docker exec 26d4846180b3 cat /etc/profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "${PS1-}" ]; then
  if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi



Previous                                                    Next                                                    Home

No comments:

Post a Comment