Docker: Use sockets for communication between 2 containers

17,750

If both containers run on the same host, it's possible to share a socket between the two as they are plain files.

You can create a local docker volume and mount that volume on both containers. Then configure you program(s) to use that path.

docker volume create --name=phpfpm
docker run phpfpm:/var/phpfpm web
docker run phpfpm:/var/phpfpm app

If the socket can be generated on the host you can mount the file into both containers. This is the method used to get a docker container to control the hosts docker.

docker run -v /var/container/some.sock:/var/run/some.sock web
docker run -v /var/container/some.sock:/var/run/some.sock app
Share:
17,750
Alex Fatyeev
Author by

Alex Fatyeev

Updated on July 18, 2022

Comments

  • Alex Fatyeev
    Alex Fatyeev almost 2 years

    I have 2 Docker containers: App & Web.

    App — simple container with php application code. It is used only for storage and deliver the code to the remote Docker host.

    App image Dockerfile:

    FROM debian:jessie
    COPY . /var/www/app/
    VOLUME ["/var/www/app"]
    CMD ["true"]
    

    Web — web service container, consist of PHP-FPM + Nginx.

    Web image Dockerfile:

    FROM nginx
    
    # Remove default nginx configs.
    RUN rm -f /etc/nginx/conf.d/*
    
    # Install packages
    RUN apt-get update && apt-get install -my \
      supervisor \
      curl \
      wget \
      php5-cli \
      php5-curl \
      php5-fpm \
      php5-gd \
      php5-memcached \
      php5-mysql \
      php5-mcrypt \
      php5-sqlite \
      php5-xdebug \
      php-apc
    
    # Ensure that PHP5 FPM is run as root.
    RUN sed -i "s/user = www-data/user = root/" /etc/php5/fpm/pool.d/www.conf
    RUN sed -i "s/group = www-data/group = root/" /etc/php5/fpm/pool.d/www.conf
    
    # Pass all docker environment
    RUN sed -i '/^;clear_env = no/s/^;//' /etc/php5/fpm/pool.d/www.conf
    
    # Add configuration files
    COPY config/nginx.conf          /etc/nginx/
    COPY config/default.vhost        /etc/nginx/conf.d
    COPY config/supervisord.conf    /etc/supervisor/conf.d/
    COPY config/php.ini             /etc/php5/fpm/conf.d/40-custom.ini
    
    VOLUME ["/var/www", "/var/log"]
    
    EXPOSE 80 443 9000
    
    ENTRYPOINT ["/usr/bin/supervisord"]
    

    My question: Is it possible to link Web container and App container by the socket?

    The main reason for this - using App container for deploy updated code to remote Docker host. Using volumes/named volumes for share code between containers is not a good idea. But Sockets can help.

    Thank you very much for your help and support!