Docker基础命令

Docker常用命令


1. 容器

1
2
3
4
5
#查看正在运行中的容器
$ docker ps

#删除正在运行的容器
$ docker rm container_id

2. 镜像

1
2
3
4
5
6
7
8
9
10
11
#查看本地所有的镜像
$ docker images

#删除镜像
$ docker rmi image_id

#从远程服务器下载镜像到本地
$ docker pull ubuntu:latest

#在远程服务器上搜索镜像
$ docker search ubuntu

3. 容器的运行

3.1 交互式运行

1
2
3
4
5
6
7
8
9
10
11
12
$ docker run -t -i 

#--interactive告诉docker保持stdin对容器开放
#--tty告诉docker为容器分配一个虚拟终端
$ docker run --tty --interactive

$ docker run -t -i ubuntu:jay /bin/bash
root@d36411ab2342:/# uname -a
Linux d36411ab2342 4.9.49-moby #1 SMP Wed Sep 27 23:17:17 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

#run bash -c "..."
$ docker run 44a8e1a5c0b2 /bin/bash -c "while true; do echo hello world; sleep 1; done"

3.2 查看容器内部的标准输出

1
2
3
4
$ docker logs container_id

#显示整个日志/跟踪显示所有日志
$ docker logs -f(--follow) container_id

3.3 查看容器内部运行的进程

1
$ docker top container_id

3.4 以后台的daemon运行

1
2
3
4
5
6
7
8
9
10
11
12
13
$ docker run -d

$ docker run --detach

$ docker run -d ubuntu:jay /bin/sh -c "while true;do echo hello-world;sleep 1;done"

$ docker logs 56d88f7bdbb1
hello-world
hello-world
hello-world
hello-world
hello-world
...

3.5 停止容器

1
$ docker stop contained_id

3.6 重启容器

1
$ docker start container_id

3.7 删除容器

1
2
#删除之前必须确保容器已经stop, 否则需要加上-f 
$ docker rm container_id -f

3.8 导入导出容器

1
2
3
4
5
$ docker export -o exportedName.tar container_id

$ docker import exportedName.tar : 导入容器快照到本地镜像库

$ docker load : 导入镜像文件到本地镜像库

4. 创建镜像

4.1 从已有的镜像创建新镜像

1
2
3
4
5
$ docker run -t -i ubuntu:15.10 /bin/bash
root@e218edb10161:/# apt update
...

$ docker commit -m="updated ubuntu" -a="Jay" container_id ubuntu:jay

4.2 docker build

  • 首先构建Dockerfile文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    FROM centos:latest
    MAINTAINER Jay "24jay@com"

    RUN /bin/echo 'root:123456' |chpasswd
    RUN yum install mariadb-server mariadb


    EXPOSE 80
    EXPOSE 8080
    EXPOSE 22
    EXPOSE 8443
    EXPOSE 3306
  • 构建

    1
    2
    3
    $ docker build

    $ docker build -t ubuntu:jay

5. Docker操作

1
2
3
4
5
6
#把本地文件复制到本地docker中
$ docker ps
$ docker cp test.sh f529a0c3adb54cf6143a5cfab77585c21cd5257cb7f3ef30f2ae9274d8510a00:/root/

#把docker中的文件复制到本地
$ docker cp f529a0c3adb54cf6143a5cfab77585c21cd5257cb7f3ef30f2ae9274d8510a00:/root/test .

6. Docker with 数据库

6.1 在容器中启动一个MySQL实例, 配置端口映射, 接下来就可以通过该端口和localhost IP进行连接

1
$ docker run -e MYSQL_ALLOW_EMPTY_PASSWORD=true -p 3306:3306 -d container_id

6.2 使用MySQL镜像作为客户端, 连接远程MySQL服务

1
2
3
# --rm : clean up
# If instead you’d like Docker to automatically clean up the container and remove the file system when the container exits, you can add the --rm flag
$ docker run -it --rm 44a8e1a5c0b2 mysql -h my.host.io -u username -p