Reputation: 1206
I am trying to prepare a docker-compose file that stands up 2 containers. They are postgres and python app inside an alpine image. Just consider before reading ı need to use python inside alpine.
My Dockerfile is:
FROM python:3
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "python", "./app.py" ]
My app.py file:
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute ("SELECT * FROM my_table;")
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
I started python container with that command:
docker run -it my_image app.py
I seperately started 2 container(postgres and python) and make it worked. However my container works only once and its job is to make an select
job inside postgresql database.
That was first part. My main goal is below.
For the simplicity i prepared a docker-compose.yml file:
version: '3'
services:
python:
image: python
build:
context: .
dockerfile: Dockerfile
postgres:
image: postgres:${TAG:-latest}
build:
context: .
environment:
POSTGRES_PASSWORD: example
ports:
- "5435:5432"
networks:
- postgres
networks:
postgres:
My dockerfile is here
When i type docker-compose up my postgres starts but python exits with code 0.
my_file_python_1 exited with code 0
What should i do for stands alone container for python apps with docker-compose? It always works only once. I can make it work constantly with
docker run -d -it my_image app.py
But my goal is to make it with docker-compose.
Upvotes: 0
Views: 4917
Reputation: 1085
version: '3'
services:
python:
image: python
build:
context: .
dockerfile: Dockerfile
postgres:
image: postgres:${TAG:-latest}
build:
context: .
environment:
POSTGRES_PASSWORD: example
ports:
- "5435:5432"
networks:
- postgres
networks:
postgres:
tty: true
If exit code is 0 means container exited after all execution, means you have to run the process in foreground to keep container running. if exit code is other than 0, means it is exiting because of code issue. so try to run any foreground process.
Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?
Upvotes: 1