当前位置: 动力学知识库 > 问答 > 编程问答 >

install mysql in docker and expose mysql service to outside

问题描述:

I am learning docker these days. And I want to install mysql inside docker container.

Here is my Dockerfile

FROM ubuntu:14.04

ADD ./setup_mysql.sh /setup_mysql.sh

RUN chmod 755 /setup_mysql.sh

RUN /setup_mysql.sh

EXPOSE 3306

CMD ["/usr/sbin/mysqld"]

and shell script setup_mysql.sh

apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sed -i -e "s/^bind-address\s*=\s*127.0.0.1/bind-address = 0.0.0.0/" /etc/mysql/my.cnf

service mysql start &

sleep 5

echo "UPDATE mysql.user SET password=PASSWORD('rootpass') WHERE user='root'" | mysql

echo "CREATE DATABASE devdb" | mysql

echo "GRANT ALL ON devdb.* TO devuser @'%' IDENTIFIED BY 'devpass'" | mysql

sleep 5

service mysql stop

Something wrong happend when running sudo docker build -t test/devenv .

Setting up mysql-server-5.5 (5.5.38-0ubuntu0.14.04.1) ...

invoke-rc.d: policy-rc.d denied execution of stop.

invoke-rc.d: policy-rc.d denied execution of start.

And if I remove the second sleep 5, the command service mysql stop will throw

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Why does this happen?

Thank you!

网友答案:

I high recommend leveraging the work of others. For example checkout the Mysql image from the docker registry:

  • https://registry.hub.docker.com/_/mysql/

Here's the associated git repository files:

  • https://github.com/docker-library/mysql/blob/master/5.7

If you look into the Dockerfile you'll notice the software is being installed as expected:

.. apt-get update && apt-get install -y mysql-server="${MYSQL_VERSION}"* ..

The trick is to realize that a database instance is not the same thing as the database software, only the latter is shipped with the image. Creating DBs and loading them with data is something that is done at run-time. So that work is done by an extra script, pulled into the image and setup to be executed when you run the container:

COPY docker-entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

Hope this helps.

分享给朋友:
您可能感兴趣的文章:
随机阅读: