Deploying Geo2tz
Introduction
Geo2tz is a self-hosted REST API service that converts geographic coordinates (latitude and longitude) to timezone identifiers. This privacy-friendly solution ensures that your location data isn’t leaked to third-party services while providing accurate timezone lookups for your applications.
Built with Go, Geo2tz is lightweight, fast, and production-ready. The service uses timezone boundary data from the timezone-boundary-builder project, providing comprehensive global coverage for timezone lookups.
Key highlights of Geo2tz:
- Privacy-Friendly: Keep location coordinates private by avoiding third-party APIs
- Simple REST API: Single endpoint for timezone lookups
- Fast Lookups: Optimized for quick response times
- Global Coverage: Comprehensive timezone boundary data worldwide
- Token Authentication: Optional API token for access control
- Lightweight: Minimal resource requirements
- Production Ready: Mature and stable for production use
- Open Source: Licensed under MIT
This guide walks through deploying Geo2tz on Klutch.sh using Docker, configuring the API, and integrating it with your applications.
Why Deploy Geo2tz on Klutch.sh
Deploying Geo2tz on Klutch.sh provides several advantages:
Simplified Deployment: Klutch.sh automatically detects your Dockerfile and builds Geo2tz. Push to GitHub, and your timezone API deploys automatically.
HTTPS by Default: Klutch.sh provides automatic SSL certificates, ensuring secure API access.
GitHub Integration: Connect your configuration repository directly from GitHub for automatic updates.
Environment Variable Management: Securely configure authentication tokens through Klutch.sh’s environment variable system.
Custom Domains: Assign a custom domain for your API endpoint.
Always-On Availability: Your timezone API remains accessible 24/7 for your applications.
Privacy Preservation: Keep user location data within your infrastructure.
Prerequisites
Before deploying Geo2tz on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your Geo2tz configuration
- Basic familiarity with Docker and containerization concepts
- (Optional) A custom domain for your API
Understanding Geo2tz Architecture
Geo2tz has a simple, efficient architecture:
Go Backend: The service is written in Go for performance and minimal resource usage.
Timezone Boundary Data: Uses pre-computed timezone boundary data for lookups without external dependencies.
REST API: Simple HTTP API with JSON responses.
In-Memory Processing: Timezone lookups are performed in memory for fast response times.
Preparing Your Repository
To deploy Geo2tz on Klutch.sh, create a GitHub repository containing your Dockerfile.
Repository Structure
geo2tz-deploy/├── Dockerfile├── README.md└── .dockerignoreCreating the Dockerfile
Create a Dockerfile in the root of your repository:
FROM ghcr.io/noandrea/geo2tz:latest
# Set portENV GEO2TZ_WEB_PORT=2004
# Optional: Set authentication token# ENV GEO2TZ_WEB_AUTH_TOKEN_VALUE=your-secret-token
# Expose the API portEXPOSE 2004Advanced Dockerfile with Configuration
For more control:
FROM ghcr.io/noandrea/geo2tz:latest
# Configure portENV GEO2TZ_WEB_PORT=2004
# Enable token authenticationENV GEO2TZ_WEB_AUTH_TOKEN_VALUE=${AUTH_TOKEN}ENV GEO2TZ_WEB_AUTH_TOKEN_QUERY_PARAM=token
# Health checkHEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:2004/tz/0/0 || exit 1
EXPOSE 2004Creating the .dockerignore File
Create a .dockerignore file:
.git.github*.mdREADME.mdLICENSE.gitignore*.log.DS_Store.env.env.localEnvironment Variables Reference
| Variable | Required | Default | Description |
|---|---|---|---|
GEO2TZ_WEB_PORT | No | 2004 | Port for the API server |
GEO2TZ_WEB_AUTH_TOKEN_VALUE | No | - | Authentication token (if set, requests require token) |
GEO2TZ_WEB_AUTH_TOKEN_QUERY_PARAM | No | token | Query parameter name for auth token |
Deploying Geo2tz on Klutch.sh
Once your repository is prepared, follow these steps to deploy Geo2tz:
- Select HTTP as the traffic type
- Set the internal port to 2004 (Geo2tz’s default port)
- Detect your Dockerfile automatically
- Build the container image
- Start the Geo2tz container
- Provision an HTTPS certificate
Generate Authentication Token (Optional)
If you want to protect your API, generate a token:
openssl rand -hex 32Save this token securely.
Push Your Repository to GitHub
Initialize your repository and push to GitHub:
git initgit add Dockerfile .dockerignore README.mdgit commit -m "Initial Geo2tz deployment configuration"git remote add origin https://github.com/yourusername/geo2tz-deploy.gitgit push -u origin mainCreate a New Project on Klutch.sh
Navigate to the Klutch.sh dashboard and create a new project. Give it a descriptive name like “geo2tz” or “timezone-api”.
Create a New App
Within your project, create a new app. Connect your GitHub account if you haven’t already, then select the repository containing your Geo2tz Dockerfile.
Configure HTTP Traffic
Geo2tz serves its API over HTTP. In the deployment settings:
Set Environment Variables
In the environment variables section, add:
| Variable | Value |
|---|---|
GEO2TZ_WEB_AUTH_TOKEN_VALUE | Your secret token (optional) |
Deploy Your Application
Click Deploy to start the build process. Klutch.sh will:
Access Geo2tz
Once deployment completes, your API is available at https://your-app-name.klutch.sh. Test it with a simple request.
Using the Geo2tz API
Basic Request
Get timezone from coordinates:
curl https://your-app-name.klutch.sh/tz/40.7128/-74.0060Response Format
The API returns JSON:
{ "tz": "America/New_York", "coords": { "lat": 40.7128, "lon": -74.006 }}With Authentication
If token authentication is enabled:
curl "https://your-app-name.klutch.sh/tz/40.7128/-74.0060?token=your-secret-token"Response Fields
| Field | Type | Description |
|---|---|---|
tz | string | IANA timezone identifier |
coords.lat | number | Latitude from request |
coords.lon | number | Longitude from request |
Integration Examples
JavaScript/Node.js
async function getTimezone(lat, lon) { const response = await fetch( `https://your-app-name.klutch.sh/tz/${lat}/${lon}` ); const data = await response.json(); return data.tz;}
// Example usageconst timezone = await getTimezone(40.7128, -74.0060);console.log(timezone); // "America/New_York"Python
import requests
def get_timezone(lat, lon, token=None): url = f"https://your-app-name.klutch.sh/tz/{lat}/{lon}" params = {"token": token} if token else {} response = requests.get(url, params=params) return response.json()["tz"]
# Example usagetimezone = get_timezone(40.7128, -74.0060)print(timezone) # "America/New_York"PHP
<?phpfunction getTimezone($lat, $lon) { $url = "https://your-app-name.klutch.sh/tz/{$lat}/{$lon}"; $response = file_get_contents($url); $data = json_decode($response, true); return $data['tz'];}
// Example usage$timezone = getTimezone(40.7128, -74.0060);echo $timezone; // "America/New_York"?>Go
package main
import ( "encoding/json" "fmt" "net/http")
type TimezoneResponse struct { Tz string `json:"tz"` Coords struct { Lat float64 `json:"lat"` Lon float64 `json:"lon"` } `json:"coords"`}
func getTimezone(lat, lon float64) (string, error) { url := fmt.Sprintf("https://your-app-name.klutch.sh/tz/%f/%f", lat, lon) resp, err := http.Get(url) if err != nil { return "", err } defer resp.Body.Close()
var result TimezoneResponse json.NewDecoder(resp.Body).Decode(&result) return result.Tz, nil}Common Use Cases
User Timezone Detection
Detect user timezone from GPS:
navigator.geolocation.getCurrentPosition(async (position) => { const { latitude, longitude } = position.coords; const timezone = await getTimezone(latitude, longitude); // Use timezone for scheduling, display, etc.});Batch Processing
Process multiple coordinates:
locations = [ (40.7128, -74.0060), # New York (51.5074, -0.1278), # London (35.6762, 139.6503), # Tokyo]
timezones = [get_timezone(lat, lon) for lat, lon in locations]API Gateway Integration
Use as a microservice behind an API gateway for your larger application.
Production Best Practices
Security Recommendations
- Token Authentication: Enable for production APIs
- Rate Limiting: Implement at your API gateway if needed
- HTTPS Only: Always use HTTPS (provided by Klutch.sh)
- Token Rotation: Rotate authentication tokens periodically
Performance Tips
- Caching: Cache responses for frequently requested coordinates
- Connection Pooling: Reuse HTTP connections in your clients
- Batch Requests: Group lookups when possible
Monitoring
Consider monitoring:
- Request latency
- Error rates
- Request volume
Troubleshooting Common Issues
Invalid Timezone Response
Symptoms: API returns unexpected timezone.
Solutions:
- Verify coordinate accuracy
- Check coordinate order (lat, lon)
- Ensure coordinates are in valid range
Authentication Errors
Symptoms: 401 or 403 responses.
Solutions:
- Verify token is correct
- Check query parameter name
- Ensure token is included in request
Service Unavailable
Symptoms: 500 or timeout errors.
Solutions:
- Check container is running
- Verify port configuration
- Review container logs
Additional Resources
Conclusion
Deploying Geo2tz on Klutch.sh gives you a private, fast timezone lookup API with automatic builds and secure HTTPS access. The combination of Geo2tz’s lightweight design and Klutch.sh’s deployment simplicity means you can have a production-ready timezone API running in minutes.
With a simple REST interface and optional authentication, Geo2tz integrates easily into any application needing timezone lookups from coordinates. Whether you’re building location-aware features or processing geographic data, Geo2tz on Klutch.sh delivers reliable timezone information while keeping your users’ location data private.