title: Start docker container on incoming HTTP request
body: <p>I have a server running multiple web applications inside separate docker containers. I am using <a href="http://traefik.io" rel="noreferrer">Traefik</a> as a reverse proxy. So, whenever a container is idle for, say 15 mins, I stop the container from inside (end the running process which causes the container to stop). How can I restart the container on demand, i.e., when there is an incoming request for the stopped container?</p>
  
  <p>As asked, I am not using any cluster manager or anything like that. Basically, I have an API server which uses the <a href="https://docker-py.readthedocs.io" rel="noreferrer">docker-py</a> library to create images and containers. Traefik listens to the docker events and generates configuration whenever a container is created to route URLs to respective containers.</p>
  
  <p>I tried systemd socket activation. Here are the socket and service files.</p>
  
  <p><strong>app.socket</strong></p>
  
  <pre><code>[Unit]
  Description=App Socket
  
  [Socket]
  ListenStream=3000
  Accept=yes
  
  [Install]
  WantedBy=sockets.target
  </code></pre>
  
  <p><strong>app@.service</strong></p>
  
  <pre><code>[Unit]
  Description=App Service
  Requires=app.socket
  
  [Service]
  Type=simple
  ExecStart=/usr/bin/npm start --prefix /path/to/dir
  StandardInput=socket
  StandardError=journal
  TimeoutStopSec=5
  
  [Install]
  WantedBy=multi-user.target
  </code></pre>
  
  <p>This is my current approach. My containers are running node apps. So, I end the node process inside the containers. While ending the node process, I'll enable and start <strong>app.socket</strong>. And when there is incoming traffic on port 3000, my apps will be started by socket activation.</p>
  
  <p>But nothing happens when I try to access that port. I've confirmed that socket activation is working. When I execute the command <code>date | netcat 127.0.0.1 3000</code>, the app seems to start and then immediately stops without any error.</p>
  
  <p>Maybe socket activation doesn't work how I'm expecting it to. I can see that a process <code>init</code> with PID <code>1</code> is running on port 3000 after enabling <strong>app.socket</strong>. As soon as traffic comes on port 3000, I want to start my node app inside the container. But how can the app start on 3000, if there is already a process running on that port?</p>
  
  <p>Perhaps there's some way to do it with <strong>Traefik</strong> since it is the reverse proxy I am using. Is there some functionality which can allow me to execute a command or script whenever 404 occurs?</p>