从零搭建虚拟机安装docker运行postgres镜像

VirtualBox是一款简单易用还免费的开源虚拟机,VirtualBox软件体积小巧,使用时不会占用太多内存,操作简单,用户可以轻松创建虚拟机。

安装virtualBox

官方网站下载地址:https://www.virtualbox.org/wiki/Downloads

选择Windows hosts链接下载安装包。然后安装

配置虚机存放位置

创建虚拟机会占用较多的磁盘空间,在 Windows 系统下默认的虚机创建位置是在 C 盘,所以最好配置到其它地方。

启动 VirtualBox 后,通过菜单 管理 -> 全局设定,或者按下快捷键 Ctrl + g,在全局设定对话框中,修改 默认虚拟电脑位置,指定一个容量较大的磁盘。

安装vagrant

官网下载地址:Downloads | Vagrant by HashiCorp (vagrantup.com)

选择Amd64链接下载安装包。然后安装

配置 Vagrant

通过 Vagrant 创建虚机需要先导入镜像文件,也就是 box,它们默认存储的位置在用户目录下的 .vagrant.d 目录下,对于 Windows 系统来说,就是 C:\Users\用户名.vagrant.d。

如果后续可能会用到较多镜像,或者你的 C 盘空间比较紧缺,可以通过设置环境变量 VAGRANT_HOME 来设置该目录。

在 Windows 系统中,可以这样操作:新建系统环境变量,环境变量名为 VAGRANT_HOME,变量值为 D:\VirtualBox\.vagrant.d

下载虚机镜像

使用 Vagrant 创建虚机时,需要指定一个镜像,也就是 box。开始这个 box 不存在,所以 Vagrant 会先从网上下载,然后缓存在本地目录中。

Vagrant 有一个镜像网站,里面列出了都有哪些镜像可以用,并且提供了操作文档。

但是这里默认下载往往会比较慢,所以下面我会介绍如何在其它地方下载到基础镜像,然后按照自己的需要重置。如果网速较好,下载顺利的朋友可以选择性地跳过部分内容。

下面我给出最常用的两个 Linux 操作系统镜像的下载地址:

CentOS

CentOS 的镜像下载网站是: https://mirrors.ustc.edu.cn/centos-cloud/centos/8/vagrant/x86_64/images/

在其中选择自己想要下载的版本,列表中有一个 vagrant 目录,里面是专门为 vagrant 构建的镜像。选择其中的 .box 后缀的文件下载即可。这里可以使用下载工具,以较快的速度下载下来。

这里我们选择下载的是 CentOS 8 的最新版本

添加 box

接下来我们需要将下载后的 .box 文件添加到 vagrant 中。

Vagrant 没有 GUI,只能从命令行访问,先启动一个命令行,然后执行:

$ vagrant box list
There are no installed boxes! Use `vagrant box add` to add some.

提示现在还没有 box。如果这是第一次运行,此时 VAGRANT_HOME 目录下会自动生成若干的文件和文件夹,其中有一个 boxes 文件夹,这就是要存放 box 文件的地方。

执行 vagrant box add 命令添加 box:

PS D:\VirtualBox> vagrant box add D:\VirtualBox\box\CentOS-8.box --name centos-8
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos-8' (v0) for provider:
    box: Unpacking necessary files from: file:///D:/VirtualBox/box/CentOS-8.box
    box:
==> box: Successfully added box 'centos-8' (v0) for 'virtualbox'!

命令后面跟着的是下载的文件路径,并且通过 --name centos-8 为这个 box 指定一个名字。

后面创建虚机都需要指定这个名字,所以尽量把名字取得简短一点,同时也要能标识出这个镜像的信息(我们后面会定制自己的基础镜像,所以这里可以简单点)。

再次查询,可以看到有了一个 box:

PS D:\VirtualBox> vagrant box list
centos-8 (virtualbox, 0)

Vagrant 基本操作

新建虚机

创建一个目录,先执行 vagrant init

PS D:\VirtualBox\vagrant\centos8_docker> vagrant init centos-8
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.

其中的 centos-8 就是我们要使用的 box 名字。

这个命令只是为我们生成一个 Vagrantfile,所以,这里的名字没指定或者写错了都没关系,后面会介绍如何编辑这个 Vagrantfile 来修改。

启动虚机

我们等会再来细看这个文件,现在直接按照提示执行 vagrant up

PS D:\VirtualBox\vagrant\centos8_docker> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos-8'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos8_docker_default_1653123888221_90314
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default:
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default:
    default: This is not an error message; everything may continue to work properly,
    default: in which case you may ignore this message.
==> default: Rsyncing folder: /cygdrive/d/VirtualBox/vagrant/centos8_docker/ => /vagrant

注意到这里包含的信息:

虚机名称:centos8_docker_default_1653123888221_90314(想改?最后有提)
网卡:Adapter 1: nat,第一块网卡,NAT 模式,这是固定的
端口转发:22 (guest) => 2222 (host) (adapter 1),把虚机的 22 端口,映射到宿主机的 2222 端口上,这样就可以通过 127.0.0.1:2222 访问虚拟机了
SSH 用户名:vagrant,这里使用 private key 登录
密码也是 vagrant,但是密码方式仅供直接登录,是不能通过 SSH 登录的。

查看虚机状态

执行下面的命令可以查看虚机的状态:

PS D:\VirtualBox\vagrant\centos8_docker> vagrant status
Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.

该命令还提示了如何操作虚机,我们继续一一介绍

连接虚机

如果启动没问题,接下来执行 vagrant ssh 就能以 vagrant 用户直接登入虚机中。

PS D:\VirtualBox\vagrant\centos8_docker> vagrant ssh
[vagrant@localhost ~]$ pwd
/home/vagrant
[vagrant@localhost ~]$ exit
logout
Connection to 127.0.0.1 closed.

root 用户没有默认密码,也不能直接登录。需要 root 权限的命令可以通过在命令前添加 sudo 来执行,也可以执行 sudo -i 直接切换到 root 用户。

这时候打开 VirtualBox 程序,可以看到自动创建的虚机

我们也可以在 VirtualBox 的终端上登录系统,默认的登录用户名和密码都是 vagrant。

当然还可以使用其它的 SSH 连接工具例如 XShell,SecureCRT 连接,但是这里默认网卡使用的是 NAT 模式,没有指定 IP,实际应用并不方便,我们在后面介绍网络配置时再详细介绍如何连接虚机。

停止虚机

执行下面的命令可以关闭虚机:

PS D:\VirtualBox\vagrant\centos8_docker> vagrant halt
==> default: Attempting graceful shutdown of VM...

直接在 VirtualBox 上关闭虚机,或者直接在虚机内部执行 poweroff 命令也都是可以的。

暂停和恢复虚机

执行下面的命令可以暂停虚机:

vagrant suspend
vagrant resume

注意: 不管虚机是关闭还是暂停状态,甚至是 error 状态,都可以执行 vagrant up 来让虚机恢复运行。

重载虚机

执行下面的命令会重启虚机,并且重新加载 Vagrantfile 中的配置信息:

vagrant reload

删除虚机

最后,执行下面的命令可以彻底删除虚机,包括整个虚机文件:

vagrant destroy

注意: 在当前这个小例子中,上面所有的 vagrant 命令都需要在 Vagrantfile 所在的目录下执行。

初识 Vagrantfile

这是一个 Ruby 语法的文件,因为 Vagrant 就是用 Ruby 编写的。

这个缺省文件内容几乎都是注释,提示有哪些配置项可以修改。

刨除注释,这个文件的实际生效内容实际只有 3 行:

Vagrant.configure("2") do |config|
  config.vm.box = "centos-8"
end

自定义配置 Vagrantfile

下面我将针对这份默认的 Vagrantfile 内容,逐个讲解其中的配置含义和如何根据实际情况修改。

配置端口转发

端口转发(Port forward)又叫端口映射,就是把虚机的某个端口,映射到宿主机的端口上。这样就能在宿主机上访问到虚拟机中的服务。

例如启动虚机时,默认的 22 (guest) => 2222 (host) (adapter 1) 就是把虚机的 SSH 服务端口(22)映射到宿主机的 2222 端口,这样直接在宿主机通过 ssh 客户端访问 127.0.0.1:2222 端口就等价于访问虚拟机的 22 端口。

下面这两段配置就是教我们如何配置额外的端口转发规则,例如把 Web 服务也映射出来:

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

还有个地方需要注意,默认的 SSH 端口映射在这里没法直接修改。比如像我这样,2222 端口出现莫名问题,如果想要把 22 端口转发到其它端口如 22222,直接添加下面这样的配置是没用的:

config.vm.network "forwarded_port", guest: 22, host: 22222

它会在原来的基础上新加一个端口转发规则,而不是替代原来的,必须要先强制关闭掉默认的那条规则:

  config.vm.network "forwarded_port", guest: 22, host: 2222, id: "ssh", disabled: "true"
  config.vm.network "forwarded_port", guest: 22, host: 22222
配置私有网络

下面这段配置用来配置私有网络,实际上对应的是 VirtualBox 的主机网络,也就是 HostOnly 网络。

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  # config.vm.network "private_network", ip: "192.168.33.10"

取消注释最下面一行,就可以为虚机设置指定的私有网络地址:

config.vm.network "private_network", ip: "192.168.33.10"

如果这个网段的主机网络在 VirtualBox 中不存在,Vagrant 会在启动虚机时自动创建。

最好这个网络也不要启用 DHCP,完全由自己来分配地址,这样更加清楚。

修改完成后,执行 vagrant reload 命令重建虚机,就能看到多出来的网卡了。

私有网络实际也可以直接使用 DHCP,但是并不推荐:

config.vm.network "private_network", type: "dhcp"
配置公共网络

下面这条配置用来配置公共网络:

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

正如注释所说,这里通常对应的就是桥接网络。

配置同步文件夹

下面的配置项用来配置同步文件夹:

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"
更改虚机规格

VirtualBox 等虚拟机软件在 Vagrant 中被称为 Provider,虚机的规格等配置是和 Provider 相关的。因为 VirtualBox 用的最多,所以默认的配置提示是以 VirtualBox 举例。

如果想要了解其它 Provider 的配置,请参考 文档

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

把中间那一段取消注释,其它的可以删掉:

  config.vm.provider "virtualbox" do |vb|
    # Display the VirtualBox GUI when booting the machine
    vb.gui = true

    # Customize the amount of memory on the VM:
    vb.memory = "1024"
  end

vb.gui = true 是在虚机启动时自动打开 VirtualBox 的图形界面,这对服务器来说没什么用,直接删掉。

添加 CPU 的配置,同时修改内存大小,在vbgui中展示的名字

  config.vm.provider "virtualbox" do |vb|
    vb.cpus = 2
    vb.memory = 2048
    vb.name = "my_vm"
    vb.gui = false
  end

使用 SSH 客户端

vagrant ssh 命令虽然很方便,但是在 Windows 环境下,因为默认的命令行终端不太好用,所以往往还需要使用更专业的 SSH 客户端例如 XShell 或 SecureCRT。

默认的镜像只支持 private_key 的方式登录,vagrant/vagrant 可以在 VirtualBox 上登录系统,但是如果用来登录 SSH,会被拒绝。

当然你可以在制作镜像的时候修改 ssh 服务的配置,让它能够用密码登录,但是实际上用密钥更加方便。

先使用 vagrant ssh-config 命令可以看到 SSH 的配置:

$ vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 22222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile E:/VirtualBox/.vagrant.d/boxes/davy-VAGRANTSLASH-centos-7-base/0/virtualbox/vagrant_private_key
  IdentitiesOnly yes
  LogLevel FATAL

可以看到其中的 IdentityFile 就是私钥文件。

发现这个自定义 box 启动的虚机的密钥文件是固定在 VAGRANT_HOME 下的相关目录下。那么就好办了,直接在 SSH 客户端软件上导入这个私钥文件就可以了。

安装docker

手动安装

  1. 先卸载旧版本

    较旧的 Docker 版本称为 docker 或 docker-engine 。如果已安装这些程序,请卸载它们以及相关的依赖项。

    $ sudo yum remove docker \
                      docker-client \
                      docker-client-latest \
                      docker-common \
                      docker-latest \
                      docker-latest-logrotate \
                      docker-logrotate \
                      docker-engine
    
  2. 添加镜像源(这里是阿里的镜像源)

    sudo yum-config-manager --add-repo  http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
    
  3. 安装依赖

    sudo yum -y install  yum-utils device-mapper-persistent-data lvm2
    
  4. 安装安装 Docker Engine-Community

    sudo yum install docker-ce docker-ce-cli containerd.io
    
  5. 查看docker 版本

    docker --version
    
  6. 启动 Docker

    sudo systemctl start docker
    
  7. 通过运行 hello-world 映像来验证是否正确安装了 Docker Engine-Community 。

    sudo docker run hello-world
    
  8. 配置docker 镜像加速

    /etc/docker/daemon.json
    #写入以下内容
    {"registry-mirrors":["https://reg-mirror.qiniu.com/","https://docker.mirrors.ustc.edu.cn/","https://hub-mirror.c.163.com/"]}
    
    重启docker
    sudo systemctl restart docker
    查看配置是否生效
    Registry Mirrors:
      https://reg-mirror.qiniu.com/
      https://docker.mirrors.ustc.edu.cn/
      https://hub-mirror.c.163.com/
    

docker安装postgresql

  1. 拉取最新的postgresql 镜像

    docker pull postgres
    
  2. 创建data目录

    mkdir -p /opt/postgresql/data
    
  3. 运行容器

    docker run -it --name postgresql --restart always -e POSTGRES_PASSWORD=123456 -e ALLOW_IP_RANGE=0.0.0.0/0 -v /opt/postgresql/data:/var/lib/postgresql -p 5432:5432 -d postgres
    
    参数说明:
    
    1.run,创建并运行一个容器;
    
    2. –name,指定创建的容器的名字;
    
    3. -e POSTGRES_PASSWORD=123456,指定数据库的登录口令为password;
    
    4.-e ALLOW_IP_RANGE=0.0.0.0/0,这个表示允许所有ip访问,如果不加,则非本机 ip 访问不了
    
    5.-v :进行映射,本地目录:容器内路径
    
    6. -p 5432:5432,映射端口,宿主机端口:容器端口,端口映射将容器的5432端口映射到外部机器的54321端口。
    
    7. -d postgres,指定使用postgres作为镜像。
    
  4. 进入容器

    先docker ps看一下容器是否起来了

    [root@localhost postgresql]# docker exec -it postgresql /bin/bash
    root@8555d98104cb:/# su postgres
    postgres@8555d98104cb:/$ psql
    psql (14.1 (Debian 14.1-1.pgdg110+1))
    Type "help" for help.
    
    postgres=# SELECT * FROM pg_database;
      oid  |  datname  | datdba | encoding | datcollate |  datctype  | datistemplate | datallowconn | datco
    nnlimit | datlastsysoid | datfrozenxid | datminmxid | dattablespace |               datacl
    
    -------+-----------+--------+----------+------------+------------+---------------+--------------+------
    --------+---------------+--------------+------------+---------------+----------------------------------
    ---
     13757 | postgres  |     10 |        6 | en_US.utf8 | en_US.utf8 | f             | t            |
         -1 |         13756 |          727 |          1 |          1663 |
         1 | template1 |     10 |        6 | en_US.utf8 | en_US.utf8 | t             | t            |
         -1 |         13756 |          727 |          1 |          1663 | {=c/postgres,postgres=CTc/postgre
    s}
     13756 | template0 |     10 |        6 | en_US.utf8 | en_US.utf8 | t             | f            |
         -1 |         13756 |          727 |          1 |          1663 | {=c/postgres,postgres=CTc/postgre
    s}
    (3 rows)
    
    
  5. 可以使用dbeaver连接postgre

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容