Docker容器互联实操--ubuntu篇

1.下载镜像

# docker pull ubuntu

2.创建容器(可联网)

# docker run -itd --net=host --name=test ubuntu /bin/bash

3.优化容器

此时容器中一些常用命令如vim ifconfig ping都没有,在本地主机创建文件sources.list,内容为

deb http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-backports main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ bionic-proposed main restricted universe multiverse

将apt源文件拷贝到容器中

# docker cp sources.list test:/etc/apt/sources.list

进入容器,安装相关命令包

# docker run -it test /bin/bash
$ apt-get update
$ apt-get install net-tools
$ apt-get install iputils-ping
$ apt-get install vim

4.打包容器并导入镜像

# docker export test > test.tar
# cat test.tar | docker import - test:v1

5.新建Docker网络

# docker network create -d bridge test-net  (-d 指定网络类型,有 bridge、overlay)
# docker network ls

6.创建两个连接到此网络的容器

# docker run -itd --name test1 --network test-net test:v1 /bin/bash
# docker run -itd --name test2 --network test-net test:v1 /bin/bash

7.进入容器进行测试

# docker exec -it test1 /bin/bash
$ ping test2

 8.配置DNS

在本地主机的/etc/docker/daemon.json文件中,可以设置所有容器的DNS

{
  "dns" : [
    "114.114.114.114",
    "8.8.8.8"
  ]
}

注:配置完后需重新启动docker

或者在创建容器时,指定dns

# docker run -it --rm -h hostname --dns=8.8.8.8 ubuntu

--rm:容器退出时自动清理容器内部的文件系统。

-h HOSTNAME 或者 --hostname=HOSTNAME: 设定容器的主机名,它会被写到容器内的 /etc/hostname 和 /etc/hosts。

 

posted @ 2021-03-26 16:49  盗哥泡茶去了  阅读(438)  评论(0编辑  收藏  举报