title: Connect to mysql in a docker container from the host
body: <p><em>(It's probably a dumb question due to my limited knowledge with Docker or mysql administration, but since I spent a whole evening on this issue, I dare to ask it.)</em></p>
  
  <p><strong>In a nutshell</strong></p>
  
  <p>I want to run mysql in a docker container and connect to it from my host. So far, the best I have achieved is:</p>
  
  <pre><code>ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
  </code></pre>
  
  <p><strong>More details</strong></p>
  
  <p>I'm using the following <code>Dockerfile</code>:</p>
  
  <pre><code>FROM ubuntu:14.04.3
  RUN apt-get update &amp;&amp; apt-get install -y mysql-server
  
  # Ensure we won't bind to localhost only
  RUN grep -v bind-address /etc/mysql/my.cnf &gt; temp.txt \
    &amp;&amp; mv temp.txt /etc/mysql/my.cnf
  
  # It doesn't seem needed since I'll use -p, but it can't hurt
  EXPOSE 3306
  
  CMD /etc/init.d/mysql start &amp;&amp; tail -F /var/log/mysql.log
  </code></pre>
  
  <p>In the directory where there is this file, I can succesfully build the image and run it with:</p>
  
  <pre><code>&gt; docker build -t my-image .
  &gt; docker run -d -p 12345:3306 my-image
  </code></pre>
  
  <p>When I attach to the image, it seems to work just fine:</p>
  
  <pre><code># from the host
  &gt; docker exec -it &lt;my_image_name&gt; bash
  
  #inside of the container now
  $ mysql -u root
  Welcome to the MySQL monitor.  Commands end with ; or \g.
  [...]
  </code></pre>
  
  <p>However I don't have that much success from the host:</p>
  
  <pre><code>&gt; mysql -P 12345 -uroot
  ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
  </code></pre>
  
  <p><strong>Even more details</strong></p>
  
  <ul>
  <li>I've seen that there's a question which <a href="https://stackoverflow.com/q/25069860/1796345">looks like mine</a>. However, it isn't the same (and it doesn't have any answers anyway)
  
  <ul>
  <li>I've seen that there are images <a href="https://github.com/sameersbn/docker-mysql" rel="noreferrer">dedicated to mysql</a>, but I didn't have more success with them</li>
  <li>My <code>grep -v</code> may feel weird. Admittedly, there may be cleaner way to do it. But when I attach my image, I can observe it actually worked as expected (ie: removed the <code>bind-address</code>). And I can see in the container <code>/var/log/mysql/error.log</code>:</li>
  </ul></li>
  </ul>
  
  <blockquote>
    <p>Server hostname (bind-address): '0.0.0.0'; port: 3306
          - '0.0.0.0' resolves to '0.0.0.0';
        Server socket created on IP: '0.0.0.0'.</p>
  </blockquote>