How can I create a Docker container whose timezone matches that of my local machine?

Viewed 3074

I'm using Docker 19. I have the following Dockerfile. Notice how I set the time zone to US EST ...

FROM microsoft/mssql-server-linux:latest
  
RUN apt-get update
RUN apt-get install unzip -y

RUN apt-get install tzdata
ENV TZ=America/New_York
RUN ln -fs /usr/share/zoneinfo/$TZ /etc/localtime && dpkg-reconfigure -f noninteractive tzdata
...

Is there any way I can author my file such that the time zone gets set to the local machine that it's running on? I'm on Central time zone but have team mates in other time zones. If it's useful, the above is part of a docker-compose file that looks roughly like this ...

version: "3.2"
services:

  sql-server-db:
    build: ./
    container_name: sql-server-db
    image: microsoft/mssql-server-linux:2017-latest
    ports:
      - 1433:1433

Some of us are on Macs, but it's possible for folks to be on Windows or Ubuntu. If it's easier you can consider that everyone is on Macs.

3 Answers

using docker run command:

-e TZ=`ls -la /etc/localtime | cut -d/ -f8-9`

Source

if you still want to use volumes you need to share /etc form the Docker UI in your MAC "Prefernces --> Resources --> FILE SHARING"

Update

for docker-compose :

under build section use:

args:
  - TZ

and then:

environment:
    - TZ=${TZ}

and then start it like - after re-build -:

export TZ=`ls -la /etc/localtime | cut -d/ -f8-9` && docker-compose up -d --build

you can set the time zone whatever you want in your host machine then you can map your local time to the container through volume mapping. Like this,

volumes:
    - /etc/localtime:/etc/localtime

For mac the location of localtime could be different. You can mount that location through volume mapping.

If it's okay to use a script to do docker-compose jobs, I think a workaround could be to set current timezone inside a shell variable, and pass it as an environment variable to containers.

The script would be:

TIMEZONE=`cat /etc/timezone`
docker-compose up -d  # or whatever

And in docker-compose file, you use this variable:

web:
  environment:
    - TZ=${TIMEZONE}

Note: You don't need to do anything on build time to set timezone. You can pass a TZ environment variable to the container and the timezone of the container would be what you want.

P.S. I'm not familiar with Mac, so /etc/timezone would be in a different location, or maybe Mac provides this value inside a predefined environment variable itself.

Related