Search code examples
bashdockercontainers

Command line shortcut to connect to a docker container


Is there any shortcut command to connect to a docker container without running docker exec -it 'container_id' bash every time?


Solution

  • Here is a shorter command line shortcut to:

    1. Check if a container is running
    2. If running, connect to a running container using docker exec -it <container> bash command:

    Script docker-enter:

    #!/bin/bash
    
    name="${1?needs one argument}"
    
    containerId=$(docker ps | awk -v app="$name:" '$2 ~ app{print $1}')
    
    if [[ -n "$containerId" ]]; then
        docker exec -it $containerId bash
    else
        echo "No docker container with name: $name is running"
    fi
    

    Then run it as:

    docker-enter webapp