Start a service inside docker CentOS 7 container - apache

I want to start the httpd service on a CentOS 7 container. But the systemctl command doesn't work in containers. In CentOS 6 I can start httpd by simply using the /etc/init.d/apachectl -d command. But in CentOS 7 I can't find any apachectl file in /*/systemd/.
So how can I start httpd service in CentOS 7 container?

The best way is to make your own centos7 image where you install httpd
FROM centos:7
RUN yum -y install httpd; yum clean all; systemctl enable httpd.service
EXPOSE 80
Build your image with docker build -t my-centos:7 .
Systemd cannot run without SYS_ADMIN. That's why I set the following vars.
$ docker run -it -p 80:80 -e "container=docker" --privileged=true -d --security-opt seccomp:unconfined --cap-add=SYS_ADMIN -v /sys/fs/cgroup:/sys/fs/cgroup:ro my-centos:7 bash -c "/usr/sbin/init"
Verify container is running:
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
967581bdf31a my-centos:7 "bash -c /usr/sbin/in" 1 seconds ago Up 1 seconds 0.0.0.0:80->80/tcp gigantic_stallman
Verifiy httpd is started
$ docker exec -it gigantic_stallman /bin/bash -c "systemctl status httpd"
● httpd.service - The Apache HTTP Server
Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2016-12-28 11:44:04 UTC; 2min 20s ago
Docs: man:httpd(8)
man:apachectl(8)
Main PID: 61 (httpd)
Status: "Total requests: 0; Current requests/sec: 0; Current traffic: 0 B/sec"
CGroup: /docker/967581bdf31a3b741a5e857720e199614d816b05a2132271f3adf910f0ed3207/system.slice/httpd.service
├─61 /usr/sbin/httpd -DFOREGROUND
├─66 /usr/sbin/httpd -DFOREGROUND
├─67 /usr/sbin/httpd -DFOREGROUND
├─68 /usr/sbin/httpd -DFOREGROUND
├─69 /usr/sbin/httpd -DFOREGROUND
└─70 /usr/sbin/httpd -DFOREGROUND
Dec 28 11:44:04 967581bdf31a systemd[1]: Starting The Apache HTTP Server...
Dec 28 11:44:04 967581bdf31a httpd[61]: AH00558: httpd: Could not reliably d...e
Dec 28 11:44:04 967581bdf31a systemd[1]: Started The Apache HTTP Server.

TL;DR: For short answer please see the other author's Answer.
My question was wrong here because it doesn't align with the containerization philosophy IMO. As these kinds of questions would be asked by new user I am going to explain a few things that's indirectly related to this question.
What is a container?
From OCI's runtime Specification, approximately,
A container contains the unit of a deliverable software.
A container will encapsulate a software component and it's dependencies.
A container should be portable and platform agnostic.
And one of the major component to achieve containerization is container runtime or in general linux container. Container runtime is a piece of software that is responsible for running containers.
Examples of a few container runtimes are, containerd, docker-engine, crio, mcr etc.
Why the question is wrong?
In general and by design, a linux container is an isolated process (these days virtual machines are also considered as containers). So in an ideal situation we should create a container just with one process which is our deliverable software.
In the question, I was thinking of using systemd to manage the process inside the container because I was neither aware about difference between a virtual machine and a container nor the principles of OCI's specification.
Also, systemd or systemV is system management daemon that is required to manage systems with hundreds or thousands of process. As the desired number of process in a container is only one so we do not need a process management daemon or any other unnecessary tools like ssh, htop, net-tools, firewalld etc.
How do we run the deliverable software?
The ideal way to run an application inside the container is to use it as the container's Entrypoint or CMD. That means, when we run the container, it will try to initiate the Entrypoint and it will start it with default command defined in the CMD. Either way, the first process (PID 1) should be our desired application/software.
So when we build the container image, we should define the entrypoint of that container. For example, I have an httpd and a redis container.
╰──➤ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
23789e2d0416 redis "docker-entrypoint.s…" 36 seconds ago Up 35 seconds 6379/tcp elegant_ganguly
9be725968ff3 httpd "httpd-foreground" 14 minutes ago Up 14 minutes 80/tcp app1
So let's check the first process of the both containers (cat /proc/1/cmdline),
╰──➤ for i in $(docker ps -q); do docker inspect $i --format 'ImageName: {{.Config.Image}}'; printf "First PID: "; docker exec -i $i sh -c "cat /proc/1/cmdline";echo; done
ImageName: redis
First PID: redis-server *:6379
ImageName: httpd
First PID: httpd-DFOREGROUND
Let's try to see the same thing with ps
╰──➤ for i in $(docker ps -q); do docker inspect $i --format 'ImageName: {{.Config.Image}}'; docker run -i --rm --pid container:$i ubuntu sh -c "ps aux | head -n2"; done
ImageName: redis
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
999 1 0.4 0.0 56024 7760 ? Ssl 14:58 0:08 redis-server *:6379
ImageName: httpd
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 7300 4380 ? Ss 14:44 0:00 httpd -DFOREGROUND
So if we are using these images; majority of the time we do not need to start it separately because it's probably already invoked by the entrypoint.
But if we want to create our own container image for our own software we can do that just by mentioning the entrypoint like the both of the httpd and redis image did here and here. You can also use CMD and Entrypoint from the command line when you run the container with the help of --entrypoint or provide the command after container name like the following (here I am using while true; do date; sleep 1; done as the default CMD),
╰──➤ docker run -d --rm ubuntu sh -c "while true; do date; sleep 1; done"
35c6352a55f25335e1bd0874493f2a31155ef752d008eb6718923d1f04ab2c14
Now let's check the first PID,
╰──➤ docker run -i --rm --pid container:35c6352a55f25 ubuntu sh -c "ps aux | head -n2"
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0 2308 832 ? Ss 15:42 0:00 sh -c while true; do date; sleep 1; done

Run the docker pull command to download the Docker image, including Apache named httpd.
#docker pull httpd
Check the docker images using
#docker images
Now run the docker command to invoke the image you downloaded.
#docker run -d --name docker-apache -p 80:80 -d httpd
Mapping the local computer's port 80 to the container's port 80 (-p 80:80).
Try to verify whether the apache web server is working by accessing the server IP or hostname in the browser.


Related

redis-server in ubuntu14.04: Bind address already in use

I started redis server on ubuntu by typing this on terminal: $redis-server
This results in following > http://paste.ubuntu.com/12688632/
aruns ~ $ redis-server
27851:C 05 Oct 15:16:17.955 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
27851:M 05 Oct 15:16:17.957 # You requested maxclients of 10000 requiring at least 10032 max file descriptors.
27851:M 05 Oct 15:16:17.957 # Server can't set maximum open files to 10032 because of OS error: Operation not permitted.
27851:M 05 Oct 15:16:17.958 # Current maximum open files is 4096. maxclients has been reduced to 4064 to compensate for low ulimit. If you need higher maxclients increase 'ulimit -n'.
27851:M 05 Oct 15:16:17.958 # Creating Server TCP listening socket *:6379: bind: Address already in use
How can I fix this problem, it there any manual or automated process to fix this binding.
$ ps aux | grep redis
Find the port that its running on.. In my case..
MyUser 8821 0.0 0.0 2459704 596 ?? S 4:54PM 0:03.40 redis-server *:6379
And then close the port manually
$ kill -9 8821
Re-run redis
$ redis-server
sudo service redis-server stop
I solved this problem on Mac by just typing redis-cli shutdown, after this just
re open the terminal and type redis-server and it will work .
for me, after lots of problems, this solved my issue:
root#2c2379a99b47:/home/ ps -aux | grep redis
redis 3044 0.0 0.0 37000 8780 ? Ssl 14:59 0:00 /usr/bin/redis-server *:6379
after finding redis, kill it!
root#2c2379a99b47:/home# sudo kill -9 3044
root#2c2379a99b47:/homek# sudo service redis-server restart
Stopping redis-server: redis-server.
Starting redis-server: redis-server.
root#2c2379a99b47:/home# sudo service redis-server status
redis-server is running
So as it says, the process is already running so the best to do is to stop it, analyse and restart it and todo so here are the following commands :
redis-cli ping #should return 'PONG'
And this solved my issue:
$ ps -ef |grep redis
root 6622 4836 0 11:07 pts/0 00:00:00 grep redis
redis 6632 1 0 Jun23 ? 04:21:50 /usr/bin/redis-server *:6379
Locate redis process, and stop it!
$ kill -9 6632
$ service redis restart
Stopping redis-server: [ OK ]
Starting redis-server: [ OK ]
$ service redis status
Otherwise if all this doesn't work just try to type redis-cli
Hope it helps :)
This works for me:
$ killall redis-server
And combining everything in one line:
$ killall redis-server; redis-server
I read the documentation on http://www.redis.io , I opened the redis.conf file to configure the redis-server, its located at /etc/redis/redis.conf
$ sudo subl /etc/redis/redis.conf
Instead of sublime editor you can use editor of your choice, viz. nano, vi, emacs, vim, gedit.
In this file I uncommented the #bind 127.0.0.1 line. Hence, instead of 0.0.0.0:6379 now its 127.0.0.1:6379
Restart the redis server
$ sudo service redis-server restart
It will state, The server is now ready to accept connections on port 6379
This will put your server up, For any more detailed configuration and settings you can follow this redis-server on ubuntu
I prefer to use the command param -ef,
ps -ef|grep redis
the -efmeans
-A Display information about other users' processes, including those
without controlling terminals.
-e Identical to -A.
-f Display the uid, pid, parent pid, recent CPU usage, process start
time, controlling tty, elapsed CPU usage, and the associated com-
mand. If the -u option is also used, display the user name
rather then the numeric uid. When -o or -O is used to add to the
display following -f, the command field is not truncated as se-
verely as it is in other formats.
then kill the pid
kill -9 $pid
You may try
$ make
then
$ sudo cp src/redis-cli /usr/local/bin/ on terminal to install the redis and it's redis-cli command.
finally, you can use the redis-cli shutdown command. Hope this answer could help you.
Killing the process that was running after booting in the OS worked for me. To prevent redis from starting at startup in Ubuntu OS:
sudo systemctl disable redis-server
In my case, I tried several times to kill the port manually and didn't work. So I took the easy path, reinstallation and worked like charm after that. If you're in Debian/Ubuntu:
sudo apt remove redis-server // No purge needed
sudo apt update
sudo apt install redis-server // Install once again
sudo systemctl status redis-server // Check status of the service
redis-server // initializes redis
Not the most technical-wise path, but nothing else worked.
It may also happen if you installed Redis via snap and are trying to run it from somewhere else.
If this is the case, you can stop the service via sudo snap stop redis.
I'm not sure, but when I first time installed redis and faced this message, turned out that's due to the redis-server first of all takes configure parameters or path/to/redis.conf, so when I passed nothing after "redis-server" it was trying to execute default redis.conf (bind 127.0.0.1, port 6379 ...) thereby overwrite the existing default redis.conf (which contains same "bind" and "port"!!). That's why I've seen this error, but it's possibly you have another reasons
The problem shows that the default port that redis uses 6379is already in use by some other process.
So simply change the port of redis server
redis-server --port 7000 will start a Redis server using port number 7000.
and then
redis-cli -p 7000 - Now use this to make your client listen at this port.

Apache server is running but httpd is not running

I'm facing a weird problem. When I access the web-accessible directory of my server via domain linked to it. It says:-
Not Found
The requested URL / was not found on this server.
When I run this command on my server (via putty), it displays few processes ids demonstrating that Apache web server is running (correct me).
root#...:~# pgrep apache
4733
13505
13506
13507
13508
13686
14199
17672
But when I run this command, it says that httpd: unrecognized service
root#...:~# service httpd status
httpd: unrecognized service
Some other commands output:-
root#...:~# ps aux|grep -i http
root 29401 0.0 0.0 6460 792 pts/0 S+ 02:21 0:00 grep --color=auto -i http
How can I fix this?
Update:-
root#...:~# chkconfig --list | grep httpd
-bash: chkconfig: command not found
root#...:~# find / -name httpd*
/var/www/vhosts/lvps5-35-241-230.dedicated.hosteurope.de/httpdocs
/var/www/vhosts/.skel/0/httpdocs
/opt/psa/var/httpd_restart
/usr/lib/apache2/modules/httpd.exp
/usr/share/doc/apache2-doc/manual/fr/programs/httpd.html
/usr/share/doc/apache2-doc/manual/pt-br/programs/httpd.html
/usr/share/doc/apache2-doc/manual/da/programs/httpd.html
/usr/share/doc/apache2-doc/manual/zh-cn/programs/httpd.html
/usr/share/doc/apache2-doc/manual/tr/programs/httpd.html
/usr/share/doc/apache2-doc/manual/en/programs/httpd.html
/usr/share/doc/apache2-doc/manual/ja/programs/httpd.html
/usr/share/doc/apache2-doc/manual/ko/programs/httpd.html
/usr/share/doc/apache2-doc/manual/de/programs/httpd.html
/usr/share/doc/apache2-doc/manual/es/programs/httpd.html
/usr/share/doc/apache2-doc/examples/apache2/original/httpd.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-autoindex.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-manual.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-userdir.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-vhosts.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-languages.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-ssl.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-mpm.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-multilang-errordoc.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-default.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-dav.conf
/usr/share/doc/apache2-doc/examples/apache2/original/extra/httpd-info.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-autoindex.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-manual.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-userdir.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-vhosts.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-languages.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-ssl.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-mpm.conf.gz
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-multilang-errordoc.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-default.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-dav.conf
/usr/share/doc/apache2-doc/examples/apache2/extra/httpd-info.conf
/etc/apache2/httpd.conf
/etc/apache2/httpd.pem
root#...:~# whereis httpd
httpd:
root#...:~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 12.04.5 LTS
Release: 12.04
Codename: precise
root#...:~# ls /etc/init.d
README hostname network-interface-container plymouth-upstart-bridge rc spamassassin udevtrigger
apache2 hwclock network-interface-security portmap rc.local ssh umountfs
bind9 hwclock-save networking portmap-wait rcS stop-bootlogd umountnfs.sh
bluetooth keymap.sh ondemand postfix reboot stop-bootlogd-single umountroot
bootlogd killprocs passwd procps rpcbind-boot sudo unattended-upgrades
console-screen.sh klogd pc-remote psa rsync sw-cp-server urandom
courier-imap module-init-tools plymouth psa-firewall saslauthd sysklogd wide-dhcpv6-client
cron modules_dep.sh plymouth-log psa-firewall-forward screen-cleanup udev x11-common
dbus mongodb plymouth-ready psa-spamassassin sendsigs udev-fallback-graphics xinetd
fetchmail mysql plymouth-splash quota single udev-finish
halt network-interface plymouth-stop quotarpc skeleton udevmonitor
root#...:~# ls /etc/xinetd.d
chargen daytime discard echo ftp_psa poppassd_psa time
Is httpd listed in your /etc/xinetd, /etc/xinet.d, /etc/xinitd.d, or /etc/init.d directory? Also use chkconfig to see if httpd is listed.
# chkconfig --list | grep httpd
If it's not:
# find / -name httpd*
or
# whereis httpd
to find where it might be installed at. Then I'd make a symbolic link to it in (depending on you linux / unix flavor) /etc/xinetd, /etc/xinet.d, /etc/xinitd.d, or /etc/init.d.

Can't start apache with supervisord from a Docker container

I'm running a Docker container with CoreOS which uses Debian latest as a base and has various packages installed including supervisor and apache2. I can start and successfully run apache using the following command:
# /usr/bin/pidproxy /var/run/apache2.pid /bin/bash -c "source /etc/apache2/envvars && /usr/sbin/apache2 -DFOREGROUND -k start"
However, when I stick this command in a supervisor config file:
[program:apache2]
command=/usr/bin/pidproxy /var/run/apache2.pid /bin/bash -c "source /etc/apache2/envvars && /usr/sbin/apache2 -DFOREGROUND -k start"
redirect_stderr=true
and do this:
# supervisorctl start apache2
I get back this response:
apache2: ERROR (abnormal termination)
Looking at the supervisor process log file I see the help output from the apache2 command, as if it had been called like so apache2 -h. I have no idea why a command which runs when executed on the command line as root (ssh into the container) would not work when verbatim executed by supervisorctl (run as root).
Any point in the right direction would be greatly appreciated.
Not really sure why, but adding quotes to my option values seems to have done the trick, and allowed me to use apachectl. Must be something with the context in which the command is interpreted, whatever supervisor is doing vs input from a bash prompt. Here's my working config file:
[program:apache2]
command=apachectl -D "FOREGROUND" -k start
redirect_stderr=true
You really want to use this. If you don't use pidproxy, a supervisorctl stop apache will not kill all it's children.
This will also make sure that the container will quit when it gets a SIGTERM instead of waiting for a SIGKILL.
[program:apache]
command=/usr/bin/pidproxy /var/run/apache2/apache2.pid /bin/bash -c "/usr/sbin/apache2ctl -D FOREGROUND"
autorestart=true
This is what works for me (using an ubuntu base image, but that should not matter):
Dockerfile:
# Pull Ubuntu as base image
FROM dockerfile/ubuntu
...
# Install supervisor to allow starting mutliple processes
RUN apt-get -y install supervisor && \
mkdir -p /var/log/supervisor && \
mkdir -p /etc/supervisor/conf.d
RUN mkdir /var/log/supervisord
# Add supervisor configuration
ADD etc/supervisor/supervisor.conf /etc/supervisor.conf
# Install Apache and enable CGI
RUN apt-get install -y apache2
ADD etc/apache/000-default.conf /etc/apache2/sites-available/000-default.conf
RUN a2enmod cgi
....
supervisor.conf
[supervisord]
; supervisord log file
logfile=/var/log/supervisord/supervisord.log
; info, debug, warn, trace
loglevel=debug
; pidfile location
pidfile=/var/run/supervisord.pid
; run supervisord as a daemon
nodaemon=false
; number of startup file descriptors
minfds=1024
; number of process descriptors
minprocs=200
; default user
user=root
; where child log files will live
childlogdir=/var/log/supervisord/
[unix_http_server]
file=/var/run/supervisor.sock ; (the path to the socket file)
; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface
[supervisorctl]
serverurl=unix:///var/run/supervisor.sock ; use a unix:// URL for a unix socket
; Apache server
[program:apache2]
command=/usr/sbin/apache2ctl -D FOREGROUND
environment=APACHE_LOG_DIR=/var/log/apache2
redirect_stderr=true
In CentOS apache is Called httpd not apache2
Your supervisor conf file will need to be updated for CentOS
/usr/sbin/httpd is the program location.
[program:apache2]
command=/usr/bin/pidproxy /var/run/httpd.pid /bin/bash -c "/usr/sbin/httpd -DFOREGROUND -k start"
redirect_stderr=true

Redis Daemon not creating a PID file

The Redis startup script is supposed to create a pid file at startup, but I've confirmed all the settings I can find, and no pid file is ever created.
I installed redis by:
$ yum install redis
$ chkconfig redis on
$ service redis start
In my config file (/etc/redis.conf) I checked to make sure these were enabled:
daemonize yes
pidfile /var/run/redis/redis.pid
And in the startup script (/etc/init.d/redis) there is:
exec="/usr/sbin/$name"
pidfile="/var/run/redis/redis.pid"
REDIS_CONFIG="/etc/redis.conf"
[ -e /etc/sysconfig/redis ] && . /etc/sysconfig/redis
lockfile=/var/lock/subsys/redis
start() {
[ -f $REDIS_CONFIG ] || exit 6
[ -x $exec ] || exit 5
echo -n $"Starting $name: "
daemon --user ${REDIS_USER-redis} "$exec $REDIS_CONFIG"
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $name: "
killproc -p $pidfile $name
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
These are the settings that came by default with the install. Any idea why no pid file is created? I need to use it for Monit.
(The system is RHEL 6.4 btw)
For those experiencing on Debian buster:
Editing
nano /etc/systemd/system/redis.service
and adding this line below redis [Service]
ExecStartPost=/bin/sh -c "echo $MAINPID > /var/run/redis/redis.pid"
It suppose to look like this:
[Service]
Type=forking
ExecStart=/usr/bin/redis-server /etc/redis/redis.conf
ExecStop=/bin/kill -s TERM $MAINPID
ExecStartPost=/bin/sh -c "echo $MAINPID > /var/run/redis/redis.pid"
PIDFile=/run/redis/redis-server.pid
then:
sudo systemctl daemon-reload
sudo systemctl restart redis.service
Check redis.service status:
sudo systemctl status redis.service
The pid file now should appear.
On my Ubuntu 18.04, I was getting the same error.
Error reported by redis (on /var/log/redis/redis-server.log):
# Creating Server TCP listening socket ::1:6379: bind: Cannot assign requested address
This is because I've disabled IPv6 on this host and redis-server package (version 5:4.0.9-1) for Ubuntu comes with:
bind 127.0.0.1 ::1
Editing /etc/redis/redis.conf and removing the ::1 address solves the problem. Example:
bind 127.0.0.1
Edit: As pointed out in the comments (thanks to #nicholas-vasilaki and #tommyalvarez), by default redis only allows connections from localhost. Commenting all the line, using:
# bind 127.0.0.1 ::1
works, but makes redis listen from the network (not only from localhost).
More details can be found in redis configuration file.
Problem was that the user redis did not have permission to create the pid file (or directory it was in). Fix:
sudo mkdir /var/run/redis
sudo chown redis /var/run/redis
Then I killed and restarted redis and sure enough, there was redis.pid
In CentOs 7 i need to add to the file:
$ vi /usr/lib/systemd/system/redis.service
The next line:
ExecStartPost=/bin/sh -c "echo $MAINPID > /var/run/redis/redis.pid"
And then restart the service:
$ sudo systemctl daemon-reload
$ sudo systemctl restart redis.service
Reference:
CentOs 7: Systemd & PID File
i had a similar problem on Debian Buster, systemd complains about the missing PID file, even though the file exists and redis is running.
on my system the solution using "echo $MAINPID > /run/redis/redis.pid" works by accident, although/because the real PID file is set to /run/redis/redis-server.pid (spot the different filenames!) and on my system the content of /run/redis/redis.pid (the one of the echo) was empty.
in a discussion on systemd-devel#lists.freedesktop.org someone writes:
... systemd will add the MAINPID environment variable any time it
knows what the main PID is. It learns this by reading the PID file ...
So by the time ExecStartPost runs, the main PID may or may not be
known.
having an empty MAINPID environment variable can be even harmful: if you notice the different PID filenames in the suggested solution, and correct it, you may end up in a situation where the PID file written by redis gets overwritten by an empty file. this happened to me, the result was that systemctl start redis.service never finished.
i also noticed that another server with 100% same OS and configuration, but different hardware did not have this problem.
my conclusion is that it just hits some sort of race condition, systemd seems to look for a PID file just a little too early. on my system, whatever command i used as ExecStartPost, it will add enough delay to make the error disappear.
therefore a solution is to use "sleep 1" (sleep 0.1 works too, but 1 second may be on the safe side):
ExecStartPost=/bin/sleep 1
/etc/systemd/system/redis.service now looks like:
[Service]
Type=forking
ExecStart=/usr/bin/redis-server /etc/redis/redis.conf
ExecStartPost=/bin/sleep 1
ExecStop=/bin/kill -s TERM $MAINPID
PIDFile=/run/redis/redis-server.pid
...
an alternative solution is to use "supervised systemd":
/etc/redis/redis.conf:
# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
# supervised no - no supervision interaction
# supervised upstart - signal upstart by putting Redis into SIGSTOP mode
# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
# supervised auto - detect upstart or systemd method based on
# UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
# They do not enable continuous liveness pings back to your supervisor.
supervised systemd
override the redis-server.service file using:
systemctl edit redis-server.service
and enter the following:
[Service]
Type=notify
reload the service and the error should be gone:
sudo systemctl restart redis.service
sudo systemctl status redis.service
Here from 2018
Before start, I am on Ubuntu 18.04.I wrote this if anyone comes here
by searching same error.
In my case error is the same but problem is so different. No solutions that proposed here worked.
So I checked logs if they are exist and looked for is there anything useful. Found them on;
cat /var/log/redis/redis-server.log
Searched logs and found that problem is that another service is listening same port.
2963:C 21 Sep 11:07:33.007 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
2963:C 21 Sep 11:07:33.008 # Redis version=4.0.9, bits=64, commit=00000000, modified=0, pid=2963, just started
2963:C 21 Sep 11:07:33.008 # Configuration loaded
2974:M 21 Sep 11:07:33.009 # Creating Server TCP listening socket 127.0.0.1:6379: bind: Address already in use
I checked who is listening.
netstat anp | grep 6379
Found it.
tcp6 0 0 :::6379 :::* LISTEN 3036/docker-proxy
It was docker image of redis that installed by another tool
root#yavuz:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a6a94d401700 redis:3.2 "docker-entrypoint.s…" 20 hours ago Up 3 hours 0.0.0.0:6379->6379/tcp incubatorsuperset_redis_1
So I stopped docker image
root#yavuz:~# docker stop incubatorsuperset_redis_1
And redis-server started without problem.
root#yavuz:~# systemctl start redis-server
root#yavuz:~# systemctl status redis-server
● redis-server.service - Advanced key-value store
Active: active (running) since Fri 2018-09-21 11:10:34 +03; 1min 49s ago
Process: 3671 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf (code=exited, status=0/SUCCESS)
For CentOS:
In my case name of Redis server is redis.service, start it edit
systemctl edit redis.service
Add this:
[Service]
ExecStartPost=/bin/sh -c "echo $MAINPID > /var/run/redis/redis.pid"
PIDFile=/var/run/redis/redis.pid
Im my case it create file: /etc/systemd/system/redis.service.d/override.conf
After restart service:
systemctl daemon-reload
systemctl restart redis
And the pid file is:
cat /var/run/redis/redis.pid
=> 19755
sudo nano /etc/redis/redis.conf
Inside the file, find the supervised directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The supervised directive is set to no by default. Since you are running Ubuntu, which uses the systemd init system, change this to systemd.
My default, Redis does not run as a daemon, and that is why it does not create a pid file. If you look at /etc/redis/redis.conf, it says so explicitly under General.
#By default Redis does not run as a daemon. Use 'yes' if you need it...
daemonize no
So all you need to do is to change it to daemonize yes
For people struggling with getting it to work on Ubuntu 18.04 you need to edit /etc/redis/redis.conf and update the pidfile declaration to following:
pidfile "/var/run/redis/redis-server.pid"
Ubuntu 18. /var/run/redis had the wrong permissions:
drwxr-sr-x 2 redis redis 60 Apr 27 12:22 redis
Changed to 755 (drwxrwxr-x) and the pid file now appears.

Docker CentOS image does not auto start httpd

I'm trying to run a simple Docker image with Apache and a PHP program. It works fine if I run
docker run -t -i -p 80:80 my/httpd /bin/bash
then manually start Apache
service httpd start
however I cant get httpd to start automatically when running
docker run -d -p 80:80 my/httpd
Apache will startup then container exists. I have tried a bunch of different CMDs in my docker file
CMD /etc/init.d/httpd start
CMD ["service" "httpd" "start"]
CMD ["/bin/bash", "/etc/init.d/httpd start"]
ENTRYPOINT /etc/init.d/httpd CMD start
CMD ./start.sh
start.sh is
#!/bin/bash
/etc/init.d/httpd start
However every-time docker instance will exist after apache starts
Am I missing something really obvious?
You need to run apache (httpd) directly - you should not use init.d script.
Two options:
you have to run apache in foreground: /usr/sbin/apache2 -DFOREGROUND ... (or /usr/sbin/httpd in CentOS)
you have to start all services (including apache configured as auto-run) by executing /sbin/init as entrypoint.
Add this line in the bottom of your Dockerfile to run Apache in the foreground on CentOS
ENTRYPOINT ["/usr/sbin/httpd", "-D", "FOREGROUND"]
Simple Dockerfile to run httpd on centOS
FROM centos:latest
RUN yum update -y
RUN yum install httpd -y
ENTRYPOINT ["/usr/sbin/httpd","-D","FOREGROUND"]
Commands for building images and running container
Build
docker build . -t chttpd:latest
Running container using new image
docker container run -d -p 8000:80 chttpd:latest
In the end of Dockerfile, insert below command to start httpd
# Start httpd
ENTRYPOINT ["/usr/sbin/httpd", "-D", "FOREGROUND"]
This works for me
ENTRYPOINT /usr/sbin/httpd -D start && /bin/bash