简体   繁体   中英

Docker postgres doesn't start at build

I want do use a docker container to simulate my production environment, so I installed the db and the server in the same container, and not each in his own.

This is my dockerfile:

FROM debian
RUN apt update
RUN apt install postgresql-9.6 tomcat8 tomcat8-admin -y
RUN service postgresql start
RUN service postgresql status # says postgres is down
RUN su - postgres ;
RUN createdb db_example # fails !!!
RUN psql -c "CREATE USER springuser WITH PASSWORD 'test123';"
RUN exit
RUN service tomcat8 start

COPY target/App-1.0.war /var/lib/tomcat8/webapps/

CMD ["/bin/bash"]

The problem is that the database is down so I am uable to create the user and the database.
If I start the a debian docker container and do this steps per hand everything works fine.

Thanks for your help

All the recommendations in the comments are correct, it's better to keep services in different containers.

Nevertheless and just to let you know, the problem in the Dockerfile is that starting services in RUN statements is useless. For every line in the Dockerfile, docker creates a new image. For example RUN service postgresql start , it may start postgresql during docker build, but it doesn't persist in the final image. Only the filesystem persist from one step to another, not the processes.

Every process need to be started in the entrypoint, this is the only command that's called when you exec docker run:

FROM debian
RUN apt update
RUN apt install postgresql-9.6 tomcat8 tomcat8-admin -y

COPY target/App-1.0.war /var/lib/tomcat8/webapps/

ENTRYPOINT["/bin/bash", "-c", "service postgresql start && service postgresql status && createdb db_example && psql -c \"CREATE USER springuser WITH PASSWORD 'test123';\" && service tomcat8 start && sleep infinity"]

(It may have problems with quotes on psql command)

I have the problem hat in the war file the localhost for the database war hard coded.
Thanks to Light.G , he suggested me to use --net=host for the container, so now there is one container with the database and one with the tomcat server.

This are the steps I followed.

Build the docker image

docker build -t $USER/App .

Start a postgres database

We are using the host namespace it is not possible to run another programm on the post 5432.
Start the postgres container like this:
docker run -it --rm --net=host -e POSTGRES_USER='springuser' -e POSTGRES_DB='db_example' -e POSTGRES_PASSWORD='test123' postgres

Start the tomcat

Start the App container, with this command:
docker run -it --net=host --rm $USER/App

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM