title: Docker - MySQL commands within Dockerfile using RUN (ERROR 2002)
body: <p>I am using Docker to create a dockerfile with mysql as the base image:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The dockerfile fails on the step where I try to create a database, it doesn't finish building and i receive this error:</p>
  
  <p><strong>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'</strong></p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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</p>
  
  <pre><code>RUN mysql -u root -ppassword -h 127.0.0.1 -P 3308 -e "CREATE DATABASE dbname"
  </code></pre>
  
  <p>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.</p>