Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker - MySQL commands within Dockerfile using RUN (ERROR 2002)

I am using Docker to create a dockerfile with mysql as the base image:

FROM mysql
#set root pass
ENV MYSQL_ROOT_PASSWORD password
#update linux
RUN apt-get update
#create database
RUN mysql -u root -ppassword -e "CREATE DATABASE dbname"
#install vim
RUN apt-get install vim -y

The dockerfile fails on the step where I try to create a database, it doesn't finish building and i receive this error:

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

When I remove the #create database run command the dockerfile will build and I am able to run a container from that image. I know that it isn't a problem with the mysql server as I can enter the container and run the mysql command manually with success and the service status is running.

Using an environment variable i.e MYSQL_ROOT_PASSWORD within the file also allows me to create a database successfully but this will only work with a single database, I need to be able to use the mysql command to make queries, such as creating additional databases / assigning users etc.

This may be because I need to specify the host and port of the docker container but this still does not allow me to connect

RUN mysql -u root -ppassword -h 127.0.0.1 -P 3308 -e "CREATE DATABASE dbname"

Strangely, doing this also often crashes the container and puts it in a state where it will crash again on start-up every time that I try to restart it again.

like image 615
user3495336 Avatar asked Oct 15 '25 11:10

user3495336


1 Answers

I think the issue might be that in the service hasn't started within the container used to build your Dockerfile.

  • Try starting and configuring MySQL server within a single step. As a reference please check this file: https://github.com/dockerfile/mysql/blob/master/Dockerfile
like image 101
Sven van de Scheur Avatar answered Oct 17 '25 03:10

Sven van de Scheur