$ sudo docker run -d webserverwebserver is clean image from ubuntu:14.04$ sudo docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES665b4a1e17b6 webserver:latest /bin/bash ... ... 22/tcp, 80/tcp loving_heisenberg
#!/bin/bash -xe# docker container id or name might be given as a parameterCONTAINER=$1if [[ "$CONTAINER" == "" ]]; then # if no id given simply just connect to the first running container CONTAINER=$(docker ps | grep -Eo "^[0-9a-z]{8,}\b")fi# start an interactive bash inside the container# note some containers don't have bash, then try: ash (alpine), or simply sh# the -l at the end stands for login shell that reads profile files (read man)docker exec -i -t $CONTAINER bash -l
注意事项:有些容器不包含 bash,但是 ash, sh 等。 在这些情况下 bash 应在上述脚本中替换。