首页 > 编程知识 正文

docker连接数据库(docker应用访问外部文件系统)

时间:2023-05-05 10:03:26 阅读:70822 作者:172

背景描述随着集装箱化进程的加快,分布式云计算兴起,以docker为代表的集装箱化技术解决方案正在普及,而不是传统虚拟机存在的巨大优势。 作为称不上新兴技术的技术,docker使用的技术多年前就已经存在,但docker的出现使这些技术真正组合起来,开始发挥效果。 与虚拟机解决方案相比,docker具有更少的精简主机资源、更高的可扩展性、比单独的软件安装更少的问题以及更容易部署。

特别是在当今微服务体系结构和云计算时代,docker有一个更好的舞台。

问题描述正在开发中。 项目需要数据库来存储数据,并且您可以从以下几种方法中进行选择,以断开多线程之间的联接:

安装mysql、redis或Postgres、leveldb等单独的数据库。

安装上述数据库的docker版本。

之后,考虑到安装独立软件的复杂性,我们采用了方案2。 一开始我想安装mysql的docker,但发现无法安装连接到web.py使用的mysql的驱动程序MySQLdb。 原因太旧了,很久没有更新了。 因此,我选择了docker版本的postgres。

但是,用独立的python脚本连接docker版本的postgres时出现了问题。 此博客的主要目的是解析单个脚本并成功连接到容器中的数据库。

环境安装今年双十一采购了最便宜的阿里巴巴云、单核2G、40G硬盘空间,三年300元。 当然,在普通的Linux环境中也可以测试该功能。 注意,Alibaba云(阿里巴巴云)默认占用80个端口号,阿里云屏蔽占用这个端口,使用的web.py框架需要这个端口,并关闭阿里云屏蔽缺省情况下,此博客使用的是Alibaba云服务器。

首先,更新服务器并安装相应的软件

更新服务器。 服务器实例是centos。

yum更新

yum安装*

安装python2.7。

yuminstallpython * * * (谷歌) ) )。

安装pip

安装web.py,用于连接到Postgres的测试。

pip install web.py

创建包含python测试脚本的目录

mkdir wx

安装docker版本的Postgres,读取doc,直接安装。

# start a postgres实例命令来自上述链接。 下面的命令意味着在docker上运行了Postgres实例。 容器名称为some-postgres,密码为mysecretpassword,默认简历数据库为postgres

docker run-- name some-postgres-e postgres _ password=my secret password-dpostgres

安装相应的python驱动程序。

pip安装psyco pg 2

在上述wx目录下编写以下脚本

# SQL.pyimoprtpsycopg2try : connection=psyco pg2. connect (user=' postgres ',password='root ', host=' 127.0数据库=' postgres ' ) cursor=connection.cursor (# printpostgresqlconnectionpropertiesprint (connection (record=cursor.fetchone ) )打印) youareconnectedto-),record,(n ) ) except ) exception,pyc OPG2. error (as error error (finally : # closingdatabaseconnection.if (connection ) : cursor.close ) (connection.close ) (print ) '

br> 问题诊断
用上述的脚本运行,得到结果如下:

python sql.py

/usr/lib64/python2.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
('Error while connecting to PostgreSQL', OperationalError('could not connect to server: Connection refusedntIs the server running on host "127.0.0.1" and acceptingntTCP/IP connections on port 5432?n',))
Traceback (most recent call last):
  File "sql.py", line 22, in <module>
    if(connection):
NameError: name 'connection' is not defined

前半部分的psycopg2-binary可以不予以关注,只是告诉我们这个驱动以后可能不叫这个名字了,我们暂且不管,毕竟现在可以用。

后边逐渐诊断,发现问题在于,postgres的IP不是localhost,而是docker分配的某一个IP。

那么,问题变成了,docker用的IP是什么呢?

docker ps

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
81bac6277944        postgres            "docker-entrypoint..."   18 hours ago        Up 18 hours         5432/tcp              postgres

可以注意到上边运行的容器实例,注意我的本机容器的名字是postgres。

需要查看一下这个容器实例的信息:

docker inspect postgres

 "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "131fea24669611632eb4fdceb4c475c246a7e5ffa25746defd3c4ab45d93d55f",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "5432/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/131fea246696",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "5d2a5af617dc56c11f95b874cd6e61a5f410d00b20c62e4ec1c12d13057c6234",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.4",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:04",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "e91322f0782411ef7fdb56da968e30b8c0d19c95894f8fef993431c197660239",
                    "EndpointID": "5d2a5af617dc56c11f95b874cd6e61a5f410d00b20c62e4ec1c12d13057c6234",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:04"
                }
            }
        }


可以注意到IPAddress这个字段,这个字段标明了当前这个实例的网络相关参数,需要将上述的127.0.0.1 参数换成 172.17.0.4,这个参数需要根据实际的docker实例运行的实际参数进行设置,将参数更该之后运行上述sql.py脚本。

[root@izm5eezkmfgg9tyd15gha9z wx]# python sql.py


/usr/lib64/python2.7/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>.
  """)
({'tty': '', 'sslcompression': '0', 'dbname': 'postgres', 'options': '', 'host': '172.17.0.4', 'target_session_attrs': 'any', 'user': 'postgres', 'sslmode': 'prefer', 'port': '5432', 'krbsrvname': 'postgres'}, 'n')
('You are connected to - ', ('PostgreSQL 11.1 (Debian 11.1-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit',), 'n')
PostgreSQL connection is closed


可以注意到,python脚本链接docker的postgres成功。

Note:
这个策略在Linux发行版上是成功的。
在Mac 版本上是失败的,由于在Mac宿主机上根本就ping不通容器的IP,完善有相关的教程解决这个问题。我自己没有尝试。参考,还有理论。
Windows环境没有尝试,原因是由于我自己的机子是win7,只能使用dockerToolbox,并且没有安装成功。于是放弃。


————————————————
原文链接:https://blog.csdn.net/u011233383/article/details/84387717

个人微信公众号:杂感123

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。