Getting into docker a bit deeper

  • I’ve got an asp.net core app that I’m creating and I’ve used docker to setup and deploy the app a bit more easily
  • To build the asp.net app, I’ve got a single Dockerfile which looks as follows:
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /source

COPY . .
RUN dotnet publish -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet","mywebapp-dotnet.dll"]
  • This asp.net app also makes use of a postgresql database so in order to get them both up and running I’ve made use of docker compose using the file docker-compose.yml. The compose file looks as follows:
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8123:8080"
    links:
      - "db:mywebapp-dotnet-db-1"
    environment:
      DBCONSTR: Host=mywebapp-dotnet-db-1;Database=mywebapp;Username=postgres;Password=mysecretpassword
    volumes:
      - mywebapp_logs:/var/logs/mywebapp

  db:
    image: postgres
    restart: always
    # set shared memory limit when using docker-compose
    shm_size: 128mb
    # or set shared memory limit when deploy via swarm stack
    #volumes:
    #  - type: tmpfs
    #    target: /dev/shm
    #    tmpfs:
    #      size: 134217728 # 128*2^20 bytes = 128Mb
    environment:
      POSTGRES_PASSWORD: mysecretpassword
      PGDATA: /var/lib/postgresql/data/mywebapp
    volumes:
      - mywebapp_data:/var/lib/postgresql/data/mywebapp

volumes:
  mywebapp_data:
  mywebapp_logs:
  • Some observations on the above docker compose file:
    • Volumes: In order to get data for logs and the postgresql database available from the host machine I needed to create these named volumes
    • Networking: By default docker creates a network with a unique id to allow the various services defined in the docker compose file to talk to each other. Making use of the unique id to point the asp.net core app to the postgresql db service will not be reliable as this value will be different every time the containers are recreated or will be different on different host machines (e.g. local dev vs production). There seems to be many different ways of addressing this in docker, however, I’ve taken the easiest approach of adding in the “link” property to the asp.net core service definition. The link property maps the service name to an alias, and with the way docker works, it’s able to translate the alias to the postgresql database host. Therefore I can make use of the alias in the DB connection string as well.

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *