my objective: run mongodb and and my fastapi app in two docker containers. they should be able to talk to each other, and I should be able to access fastapi API on my localhost:8000
i want to run my api server locally using docker container. normally i run my mongo db using docker, and using
docker run --rm -p 27017:27017 mongo
then I run my fastapi application using uvicorn api.main:app
now, i am running my fastapi application within docker container. here is the Dockerfile
FROM python:3.11
ENV VENV_PATH="/venv"
ENV PATH="$VENV_PATH/bin:$PATH"
WORKDIR /app
RUN apt-get update && \
apt-get install -y --no-install-recommends apt-utils && \
apt-get upgrade -y && \
apt-get autoclean
RUN pip install --upgrade poetry
RUN python -m venv /venv
COPY . .
RUN poetry build && \
/venv/bin/pip install --upgrade pip wheel setuptools &&\
/venv/bin/pip install dist/*.whl
EXPOSE 8000
CMD uvicorn api.main:app
after building the image, I run
docker run -it --env-file .env --network=host my-api
when I do the above, my application running inside docker container is able to connect to mongo db database at localhost:27017, but the 8000 port of the container is not exposed to my localhost's 8000
if i do this then my application running in docker can easily communicate with MongoDB server exposed at localhost:27017
but I need to expose my docker container's 8000 port to my local host. that I generally do with
docker run -it --env-file .env -p 8000:8000/tcp my-api
in that case the app running inside container cant access mongo db at localhost:27017
when i apply both the network and p(publish) flag, i get
WARNING: Published ports are discarded when using host network mode
i tried using two p flags, 8000:8000 and 27017:27017, and i got
Docker: Error response from daemon: driver failed programming external connectivity on endpoint goofy_ptolemy
(f67673328ee02111a16080a7f3588146981aa7974d2ea8a071815f1ae7ad774f): Bind for 0.0.0.0:27017 failed: port is already allocated.