Reputation: 416
I am running a SQL server container on Ubuntu using the following command
sudo docker run -e 'ACCEPT_EULA=Y' -e 'MSSQL_SA_PASSWORD=MyPassword' \
-p 1433:1433 --name db \
-d microsoft/mssql-server-linux:2017-latest`
I have another container on the same machine running WebAPI Core application, everything work find if i specified the server ip in the connection string but if I replaced it with "localhost" or "." it fail to connect.
Anyone faced the same issue? I don't want to modify the connection string every time I run my application on a new machine.
Edit 1: I need the my database to be up and running during the build process to apply EntityFramework code first migrations, so I cannot just add the SQL Server as a dependency in docker-compose.yml
Edit 2 Here is my docker-compose.yml
version: '3'
services:
webapi:
image: webapi
build:
context: ./
dockerfile: ./WebAPI/Dockerfile
args:
- connString=Server=db;Database...;
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://+:80
- conneString="Server=db;Database..."
ports:
- 50695:80
depends_on:
- db
db:
image: "microsoft/mssql-server-linux:2017-latest"
container_name: db
networks:
default:
external:
name: nat
And my docker file
FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80
FROM microsoft/aspnetcore-build:2.0 AS build
ARG connString
ENV connString "$connString"
WORKDIR /src
COPY *.sln ./
COPY WebAPI/WebAPI.csproj WebAPI/
RUN dotnet restore
COPY . .
WORKDIR /src/Repository
RUN dotnet restore
RUN dotnet ef database update
WORKDIR /src/WebAPI
RUN dotnet build -c Release -o /app
FROM build AS publish
RUN dotnet publish -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "WebAPI.dll"]
Upvotes: 0
Views: 2366
Reputation: 2613
Yes, you can use localhost to connect the database, which is better than IP address.
You need to link container to your database container.
If you are using docker-compose then follow example
container1:
build: image_name
links:
- mysql:mysql
container2:
build: image_name
links:
- mysql:mysql
mysql:
build: mysql
In above example you will see, I have link mysql container to every other container, by this you don't need to specify IP address.
if you are not using docker-compose then in your docker run command please use
--link sql_container_name:sql_container_name
Hope this will help you, let me know in case any issue with this?
Upvotes: 0
Reputation: 2529
First off, you generally DO want to make your connection string easily configurable (like perhaps an environment variable), as it would make sense that your application running on different machines might connect to a different database server as well.
To the point of your docker question, you might want to look into using docker compose instead of just raw docker. Compose sets up hostname aliases for all of the containers within your cluster, so you would just be able to use a hostname like db
.
Upvotes: 0