Docker MySQL无法连接到套接字

时间:2015-11-18 19:35:14

标签: mysql ruby-on-rails nginx docker passenger

我正在学习Docker,我在尝试连接passenger-full容器和mysql容器上的Rails应用时遇到了问题。两者都在撰写文件中链接

app:
  build: ./rails
  ports:
    - "80:80"
  links:
    - database
  volumes:
    - ./rails:/home/app/webapp
database:
  image: mysql
  environment:
    - MYSQL_DATABASE="dockertest"
    - MYSQL_USER="dockertest"
    - MYSQL_PASSWORD="dockertest"
    - MYSQL_ROOT_PASSWORD="root"

所以我在我的Dockerfile顶部添加了apt-get install,如下所示

FROM phusion/passenger-full
RUN apt-get update && apt-get install libmysqlclient-dev mysql-client -y

# Set correct environment variables.
ENV HOME /root

# Use baseimage-docker's init process.
CMD ["/sbin/my_init"]

RUN rm -f /etc/service/nginx/down
RUN rm /etc/nginx/sites-enabled/default
ADD webapp.conf /etc/nginx/sites-enabled/webapp.conf

RUN mkdir /home/app/webapp
WORKDIR /home/app/webapp
ADD . /home/app/webapp
RUN cd /home/app/webapp && bundle install
RUN touch /home/app/webapp/tmp/restart.txt

# Clean up APT when done.
RUN apt-get clean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

这也是我在Rails应用程序中的database.yml

default: &default
  adapter: mysql2
  database: dockertest
  host: <%= ENV['MYSQL_PORT_3306_TCP_ADDR'] %>
  port: <%= ENV['MYSQL_PORT_3306_TCP_PORT'] %>
  username: dockertest
  password: dockertest

development:
  <<: *default

production: 
  <<: *default

问题是我无法停止接收错误

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

webconf文件是

# /etc/nginx/sites-enabled/webapp.conf:
server {
    listen 80;
    server_name localhost;
    root /home/app/webapp/public;

    passenger_enabled on;
    passenger_user app;
    passenger_ruby /usr/bin/ruby2.2;
}

这是正确的方法吗?正如你所看到的,我对Docker来说还是个新手。

1 个答案:

答案 0 :(得分:4)

此处的问题是links文件中的docker-compose.yml指令。你有:

links:
  - database

根据name:alias reference,这基本上表示链接database:databasedocker-compose.yml

此外,如果您阅读linking container docs,则可以看到导出到源容器的环境的格式为ALIAS_XXX,例如ALIAS_PORT_3306_TCP_PORT。所以在你的database.yml中你想要做的事情就是这样:

default: &default
  adapter: mysql2
  database: dockertest
  host: <%= ENV['DATABASE_PORT_3306_TCP_ADDR'] %>
  port: <%= ENV['DATABASE_PORT_3306_TCP_PORT'] %>
  username: dockertest
  password: dockertest

development:
  <<: *default

production: 
  <<: *default

如果您想使用MYSQL别名,您的链接必须在docker-compose.yml文件中看起来像这样。

links:
  - database:mysql

错误:

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

基本上来自你的Rails应用程序,不是要查看database.yml中的内容并默认为本地/var/run/mysqld/mysqld.sock连接。

希望它有所帮助。