Docker搭建MySQL服務


Docker開源鏡像

前面我們已經安裝好了Docker,也簡單了解了Docker。那么我們可以嘗試搭建一個MySQL服務。

要搭建服務就要啟動服務容器,要創建容易就要有鏡像,Docker提供了一個類似Github的開源平台,提供開源鏡像,放心可靠。(畢竟大家都看着源碼呢)

Docker開源鏡像傳送門


大概步驟

1. 下載MySQL鏡像
2. 創建運行容器

好像很簡單是吧?


詳細步驟

第零步,查看Docker MySQL文檔

MySQL文檔地址:
https://hub.docker.com/_/mysql/


第一步,拉取MySQL鏡像

$ sudo docker pull mysql

之后docker會自動拉取(下載)MySQL鏡像。

等待同樣是漫長的。。。

注意,若提示拉取失敗就重復幾次,總有一次會成功的。。。沒辦法,牆內的人民很辛苦

拉取成功后我們查看一下:

$ sudo docker images

01


第二步,創建並啟動一個MySQL容器

輸入以下命令:

$ sudo docker run --name pwc-mysql -e MYSQL_ROOT_PASSWORD=123456 -p 3306:3306 -d mysql

02

  • –name:給新創建的容器命名,此處命名為pwc-mysql
  • -e:配置信息,此處配置mysqlroot用戶的登陸密碼
  • -p:端口映射,此處映射主機3306端口容器pwc-mysql的3306端口
  • -d:成功啟動容器后輸出容器的完整ID,例如上圖 73f8811f669ee...
  • 最后一個mysql指的是mysql鏡像名字

到這里我們查看容器運行狀態:

$ sudo docker ps

03

上圖可以看到容器的簡寫ID,容器的源鏡像,創建時間,狀態,端口映射信息,容器名字等。


第三步,測試連接MySQL

這里我使用navicat遠程連接,連接MySQL前需要防火牆開放端口或者關閉防火牆。

開放端口:

$ sudo firewall-cmd --add-port=3306/tcp

關閉防火牆:

$ sudo systemctl stop firewalld

接着使用navicat連接
04

連接成功,也可以進行相關數據庫操作,因此MySQL服務搭建成功!


其他

1.可以啟動多個MySQL服務,因為我們啟動的是容器,容器可以有多個,只要容器名字映射段端口不一樣就可以了,例如:

$ sudo docker run --name dbdb -e MYSQL_ROOT_PASSWORD=123456 -p 6666:3306 -d mysql

2.查看所有容器(啟動狀態或者關閉狀態)

$ sudo docker ps -a

3.啟動和關閉容器

啟動命令:

$ sudo docker start pwc-mysql   //通過指定容器名字
$ sudo docker start 73f8811f669e  //通過指定容器ID

關閉命令:

$ sudo docker stop pwc-mysql   //通過指定容器名字
$ sudo docker stop 73f8811f669e  //通過指定容器ID

3.修改MySQL配置文件有兩種方法:

  • 一是進入容器,修改容器里的MySQL的配置文件,然后重新啟動容器,例如:

    $ sudo docker exec -it pwc-mysql /usr/bin/bash

    然后可以進入容器的命令行模式,接着修改 /etc/mysql/my.cnf 文件即可

  • 二是掛載主機的mysql配置文件,官方文檔如下:

    The MySQL startup configuration is specified in the file /etc/mysql/my.cnf, and that file in turn includes any files found in the /etc/mysql/conf.d directory that end with .cnf. Settings in files in this directory will augment and/or override settings in /etc/mysql/my.cnf. If you want to use a customized MySQL configuration, you can create your alternative configuration file in a directory on the host machine and then mount that directory location as /etc/mysql/conf.d inside the mysql container.

    If /my/custom/config-file.cnf is the path and name of your custom configuration file, you can start your mysql container like this (note that only the directory path of the custom config file is used in this command):

    $ docker run --name some-mysql -v /my/custom:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=my-secret-pw -d mysql:tag

    This will start a new container some-mysql where the MySQL instance uses the combined startup settings from /etc/mysql/my.cnf and /etc/mysql/conf.d/config-file.cnf, with settings from the latter taking precedence.

我大概可以看懂,相信大家都可以的


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM