Tutorials and guides on using Docker to contain and manage web applications

How to remove a stale PID from a Docker container

Written by: Peter Fisher on May 7, 2016
Tagged under: ,
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

large_v-transOver the last few months I have been experimenting with using Docker to host some local websites. Unfortunately I have noticed that sometimes the apache2 container refuses to restart if it has stopped unexpectedly.

This is the error message from the apache2 container:

docker logs site1-apache2
httpd (pid 1) already running

I’m not sure why the old pid is still running. This error usually occurs after my laptop shuts down or goes to sleep. Perhaps the container was not stopped correctly.

So to get around this error I wrote a simple script that removes the existing PID when the container is built.

Heres the section in the DockerFile:

        APACHE_RUN_GROUP=www-data \
        APACHE_LOG_DIR=/var/log/apache2 \
        APACHE_LOCK_DIR=/var/lock/apache2 \
        APACHE_RUN_DIR=/var/run/apache2 \

COPY ./storage/scripts/* /scripts/

RUN chmod +x /scripts/*

CMD ["/scripts/"]

This does the following:

  1. Set up apache variables
  2. Copies all the scripts from ./storage/scripts/ to /scripts/
  3. Makes all the scripts executable
  4. Runs the boot script

Heres the

if [ ! -d "$APACHE_RUN_DIR" ]; then
	mkdir "$APACHE_RUN_DIR"
if [ -f "$APACHE_PID_FILE" ]; then
/usr/sbin/apache2ctl -D FOREGROUND

This does the following:

  1. Creates the $APACHE_RUN_DIR directory with correct permissions if it doesn’t exist
  2. Removes the $APACHE_PID_FILE if it exists
  3. Runs apache2ctl in the foreground

Each time I rebuild the apache2 container the old PID file is removed if its found and I can go about my day.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Peter Fisher is a web developer working in Gloucester UK. Founder of the digital agency Websomatic, author of this blog and the HowToCodeWell Youtube channel. Peter has over ten years of web development experience under his belt

Read all about Peter Fisher

Leave a Reply

Your email address will not be published. Required fields are marked *

One Response

liahim says:

Great article! You saved me a lot of time. Thank you!