背景说明

使用Docker过程中需要记住一些辅助命令,此时相对比较费脑子,这里整理了快捷命令。

解决方案

创建脚本文件idocker并放置至目录/usr/local/bin/下

  1. #!/bin/bash
  2. #example:
  3. #params $2 :第二个参数表示
  4. #idocker in mysql
  5. if [ "$1" == "reset" ];then
  6. docker stop $(docker ps -q )
  7. docker rm $(docker ps -a -q )
  8. fi
  9. if [ "$1" == "images" ];then
  10. docker images --format "table {{.Repository}}:{{.Tag}}\t{{.ID}}\t{{.CreatedAt}}"
  11. fi
  12. if [ "$1" == "ips" ];then
  13. docker inspect --format "{{.Name}} {{.Config.Image}} {{.Config.Hostname}} {{.NetworkSettings.IPAddress}}" $(docker ps -q)
  14. fi
  15. if [ "$1" == "ps" ];then
  16. docker ps --format "table {{.ID}}\t{{.Names}}\t{{.Image}}\t{{.Networks}}\t{{.Status}}\t{{.Ports}}"
  17. fi
  18. if [ "$1" == "search" ];then
  19. for Repo in $* ; do
  20. curl -s -S "https://registry.hub.docker.com/v2/repositories/library/$Repo/tags/" | \
  21. sed -e 's/,/,\n/g' -e 's/\[/\[\n/g' | \
  22. grep "name" | awk -F\" '{print $4;}' | \
  23. sort -fu | \
  24. sed -e "s/^/${Repo}:/"
  25. done
  26. fi
  27. if [ "$1" == "in" ];then
  28. docker exec -it $2 /bin/bash
  29. fi
  30. if [ "$1" == "ip" ];then
  31. docker inspect --format "{{.NetworkSettings.IPAddress}}" $2
  32. fi
  33. if [ "$1" == "volumes" ];then
  34. docker inspect --format "{{.Config.Volumes}}" $2
  35. fi
  36. if [ "$1" == "start" ];then
  37. if [ "$2" == "yii" ];then
  38. sudo /usr/local/bin/docker-compose -f /tmp/advanced/docker-compose.yml start
  39. fi
  40. fi
  41. if [ "$1" == "stop" ];then
  42. if [ "$2" == "yii" ];then
  43. sudo /usr/local/bin/docker-compose -f /tmp/advanced/docker-compose.yml stop
  44. fi
  45. fi

!/bin/bash指定shell解释器

赋予可执行权限

  1. [root@template ~]# chmod +x /usr/local/bin/idocker
  2. [root@template ~]# idocker ps
  3. CONTAINER ID NAMES IMAGE NETWORKS STATUS PORTS
  4. e47c82f7326e haproxy haproxy playwithdocker_default Up 11 hours 0.0.0.0:80->8080/tcp, :::80->8080/tcp
  5. f4f4a00cc786 pwd golang playwithdocker_default Up 11 hours
  6. 1c271864f6a2 l2 golang playwithdocker_default Up 11 hours 0.0.0.0:443->443/tcp, :::443->443/tcp, 0.0.0.0:8022->22/tcp, :::8022->22/tcp, 0.0.0.0:8053->53/tcp, :::8053->53/tcp

进入容器

  1. [root@template ~]# docker ps
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  3. d91aa5eac508 nginx "/docker-entrypoint.…" 49 minutes ago Up 49 minutes 80/tcp blissful_darwin
  4. [root@template ~]# idocker in d91aa5eac508
  5. root@d91aa5eac508:/#
  6. root@d91aa5eac508:/# exit
  7. exit
  8. [root@template ~]#

容器主机

  1. [root@template ~]# idocker ip d91aa5eac508
  2. 172.17.0.2
  3. [root@template ~]#