Fred808 commited on
Commit
bd42648
·
verified ·
1 Parent(s): ffd513e

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +288 -17
Dockerfile CHANGED
@@ -1,32 +1,303 @@
1
-
2
  FROM ubuntu:22.04
3
 
4
  ENV DEBIAN_FRONTEND=noninteractive
5
 
6
  RUN apt-get update && \
7
  apt-get install -y --no-install-recommends \
8
- wireguard \
9
- wireguard-tools \
10
- wireguard-dkms \
11
- iptables \
12
- net-tools \
13
- iproute2 \
14
- netfilter-persistent \
15
- openresolv \
16
- bash \
17
- python3 \
18
- python3-pip && \
19
  apt-get clean && rm -rf /var/lib/apt/lists/*
20
 
21
- # Enable IP forwarding
22
- RUN echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf && \
23
- echo 'net.ipv6.conf.all.forwarding=1' >> /etc/sysctl.conf
24
 
25
- # (No need to copy wg-config, config will be generated at runtime)
26
  COPY entrypoint.sh /usr/local/bin/
27
  COPY generate_wireguard_config.py /usr/local/bin/
28
- RUN chmod +x /usr/local/bin/entrypoint.sh
 
 
 
29
 
30
  ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
 
 
 
1
+ # Dockerfile
2
  FROM ubuntu:22.04
3
 
4
  ENV DEBIAN_FRONTEND=noninteractive
5
 
6
  RUN apt-get update && \
7
  apt-get install -y --no-install-recommends \
8
+ wireguard \
9
+ wireguard-tools \
10
+ iptables \
11
+ net-tools \
12
+ iproute2 \
13
+ curl \
14
+ python3 \
15
+ python3-pip \
16
+ procps && \
 
 
17
  apt-get clean && rm -rf /var/lib/apt/lists/*
18
 
19
+ # Create wireguard directory
20
+ RUN mkdir -p /etc/wireguard
 
21
 
22
+ # Copy scripts
23
  COPY entrypoint.sh /usr/local/bin/
24
  COPY generate_wireguard_config.py /usr/local/bin/
25
+ RUN chmod +x /usr/local/bin/entrypoint.sh /usr/local/bin/generate_wireguard_config.py
26
+
27
+ # Expose WireGuard port
28
+ EXPOSE 51820/udp
29
 
30
  ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
31
 
32
+ ---
33
+
34
+ # entrypoint.sh
35
+ #!/bin/bash
36
+ set -e
37
+
38
+ echo "🐳 Starting WireGuard Docker Container"
39
+ echo "======================================"
40
+
41
+ # Check if running with required capabilities and privileges
42
+ if [ ! -w /proc/sys/net/ipv4/ip_forward ] 2>/dev/null; then
43
+ echo "⚠️ Warning: Cannot write to /proc/sys - IP forwarding may not work"
44
+ echo " Make sure to run with: --sysctl net.ipv4.ip_forward=1"
45
+ else
46
+ echo "✅ Setting IP forwarding"
47
+ echo 1 > /proc/sys/net/ipv4/ip_forward
48
+ echo 1 > /proc/sys/net/ipv6/conf/all/forwarding 2>/dev/null || true
49
+ fi
50
+
51
+ # Check for NET_ADMIN capability
52
+ if ! ip link add dummy0 type dummy 2>/dev/null; then
53
+ echo "❌ ERROR: Container needs NET_ADMIN capability"
54
+ echo " Run with: docker run --cap-add=NET_ADMIN ..."
55
+ exit 1
56
+ else
57
+ ip link delete dummy0 2>/dev/null || true
58
+ echo "✅ NET_ADMIN capability confirmed"
59
+ fi
60
+
61
+ # Generate config if it doesn't exist
62
+ if [ ! -f /etc/wireguard/wg0.conf ]; then
63
+ echo "📝 Generating WireGuard configuration..."
64
+ python3 /usr/local/bin/generate_wireguard_config.py
65
+ else
66
+ echo "✅ Using existing WireGuard configuration"
67
+ fi
68
+
69
+ # Start WireGuard
70
+ echo "🚀 Starting WireGuard interface..."
71
+ wg-quick up wg0
72
+
73
+ # Show status
74
+ echo "📊 WireGuard Status:"
75
+ wg show
76
+
77
+ # Keep container running and show logs
78
+ echo "✅ WireGuard is running. Monitoring logs..."
79
+ tail -f /dev/null
80
+
81
+ ---
82
+
83
+ # generate_wireguard_config.py (Docker version)
84
+ #!/usr/bin/env python3
85
+ import os
86
+ import subprocess
87
+ import sys
88
+
89
+ WG_DIR = "/etc/wireguard"
90
+ SERVER_PRIVATE = os.path.join(WG_DIR, "privatekey")
91
+ SERVER_PUBLIC = os.path.join(WG_DIR, "publickey")
92
+ PEER_PRIVATE = os.path.join(WG_DIR, "peer1_privatekey")
93
+ PEER_PUBLIC = os.path.join(WG_DIR, "peer1_publickey")
94
+
95
+ def generate_keypair(private_path, public_path):
96
+ """Generate WireGuard key pair"""
97
+ try:
98
+ priv = subprocess.check_output(["wg", "genkey"]).decode().strip()
99
+ with open(private_path, "w") as f:
100
+ f.write(priv)
101
+ os.chmod(private_path, 0o600)
102
+
103
+ pub = subprocess.check_output(["wg", "pubkey"], input=priv.encode()).decode().strip()
104
+ with open(public_path, "w") as f:
105
+ f.write(pub)
106
+ os.chmod(public_path, 0o644)
107
+
108
+ return priv, pub
109
+ except Exception as e:
110
+ print(f"❌ Error generating keypair: {e}")
111
+ sys.exit(1)
112
+
113
+ def get_public_ip():
114
+ """Get public IP - try multiple methods for Docker"""
115
+ import urllib.request
116
+
117
+ # Check for environment variable first (best for Docker)
118
+ if 'WG_PUBLIC_IP' in os.environ:
119
+ return os.environ['WG_PUBLIC_IP']
120
+
121
+ methods = [
122
+ 'https://api.ipify.org',
123
+ 'https://ipv4.icanhazip.com',
124
+ 'https://checkip.amazonaws.com',
125
+ 'https://ifconfig.me/ip'
126
+ ]
127
+
128
+ for url in methods:
129
+ try:
130
+ with urllib.request.urlopen(url, timeout=10) as response:
131
+ ip = response.read().decode().strip()
132
+ if ip and '.' in ip and len(ip.split('.')) == 4: # Basic IP validation
133
+ return ip
134
+ except Exception as e:
135
+ print(f"⚠️ Failed to get IP from {url}: {e}")
136
+ continue
137
+
138
+ print("⚠️ Could not determine public IP automatically")
139
+ return "YOUR_PUBLIC_IP_HERE"
140
+
141
+ def create_server_config(server_priv, peer_pub):
142
+ """Create server configuration optimized for Docker"""
143
+ return f"""[Interface]
144
+ Address = 10.10.0.1/24
145
+ ListenPort = 51820
146
+ PrivateKey = {server_priv}
147
+ PostUp = iptables -t nat -A POSTROUTING -s 10.10.0.0/24 -o eth0 -j MASQUERADE
148
+ PostUp = iptables -A FORWARD -i wg0 -j ACCEPT
149
+ PostUp = iptables -A FORWARD -o wg0 -j ACCEPT
150
+ PostDown = iptables -t nat -D POSTROUTING -s 10.10.0.0/24 -o eth0 -j MASQUERADE || true
151
+ PostDown = iptables -D FORWARD -i wg0 -j ACCEPT || true
152
+ PostDown = iptables -D FORWARD -o wg0 -j ACCEPT || true
153
+
154
+ [Peer]
155
+ PublicKey = {peer_pub}
156
+ AllowedIPs = 10.10.0.2/32"""
157
+
158
+ def create_peer_config(peer_priv, server_pub, public_ip):
159
+ """Create peer configuration"""
160
+ return f"""[Interface]
161
+ PrivateKey = {peer_priv}
162
+ Address = 10.10.0.2/24
163
+ DNS = 1.1.1.1, 8.8.8.8
164
+
165
+ [Peer]
166
+ PublicKey = {server_pub}
167
+ Endpoint = {public_ip}:51820
168
+ AllowedIPs = 0.0.0.0/0
169
+ PersistentKeepalive = 25"""
170
+
171
+ def main():
172
+ print("🔧 Docker WireGuard Configuration Generator")
173
+ print("=" * 45)
174
+
175
+ # Skip root check in Docker - we run as root in container
176
+ print("🐳 Running in Docker container mode")
177
+
178
+ # Create directory (should already exist)
179
+ os.makedirs(WG_DIR, exist_ok=True)
180
+
181
+ # Generate keys
182
+ print("🔑 Generating keypairs...")
183
+ server_priv, server_pub = generate_keypair(SERVER_PRIVATE, SERVER_PUBLIC)
184
+ peer_priv, peer_pub = generate_keypair(PEER_PRIVATE, PEER_PUBLIC)
185
+ print("✅ Server and peer keypairs generated")
186
+
187
+ # Get public IP
188
+ print("🌐 Detecting public IP...")
189
+ public_ip = get_public_ip()
190
+ print(f"📍 Public IP: {public_ip}")
191
+
192
+ # Create server config
193
+ server_config = create_server_config(server_priv, peer_pub)
194
+ with open(os.path.join(WG_DIR, "wg0.conf"), "w") as f:
195
+ f.write(server_config)
196
+ os.chmod(os.path.join(WG_DIR, "wg0.conf"), 0o600)
197
+ print("✅ Server config written to wg0.conf")
198
+
199
+ # Create peer config
200
+ peer_config = create_peer_config(peer_priv, server_pub, public_ip)
201
+ with open(os.path.join(WG_DIR, "peer1.conf"), "w") as f:
202
+ f.write(peer_config)
203
+ os.chmod(os.path.join(WG_DIR, "peer1.conf"), 0o600)
204
+ print("✅ Peer config written to peer1.conf")
205
+
206
+ print("\n🎉 WireGuard configuration completed!")
207
+ print("\n📱 To get the peer config:")
208
+ print(" docker exec <container> cat /etc/wireguard/peer1.conf")
209
+
210
+ if public_ip == "YOUR_PUBLIC_IP_HERE":
211
+ print("\n⚠️ IMPORTANT: Set WG_PUBLIC_IP environment variable or")
212
+ print(" manually update the Endpoint in peer1.conf!")
213
+
214
+ if __name__ == "__main__":
215
+ main()
216
+
217
+ ---
218
+
219
+ # docker-compose.yml
220
+ version: '3.8'
221
+
222
+ services:
223
+ wireguard:
224
+ build: .
225
+ container_name: wireguard-server
226
+ cap_add:
227
+ - NET_ADMIN
228
+ - SYS_MODULE
229
+ sysctls:
230
+ - net.ipv4.ip_forward=1
231
+ - net.ipv6.conf.all.forwarding=1
232
+ ports:
233
+ - "51820:51820/udp"
234
+ volumes:
235
+ - ./wireguard-config:/etc/wireguard
236
+ - /lib/modules:/lib/modules:ro
237
+ restart: unless-stopped
238
+ privileged: true # Sometimes needed for WireGuard in containers
239
+
240
+ ---
241
+
242
+ # docker-run.sh
243
+ #!/bin/bash
244
+
245
+ # Build the image
246
+ docker build -t wireguard-server .
247
+
248
+ # Run the container
249
+ docker run -d \
250
+ --name wireguard-server \
251
+ --cap-add=NET_ADMIN \
252
+ --cap-add=SYS_MODULE \
253
+ --sysctl net.ipv4.ip_forward=1 \
254
+ --sysctl net.ipv6.conf.all.forwarding=1 \
255
+ -p 51820:51820/udp \
256
+ -v $(pwd)/wireguard-config:/etc/wireguard \
257
+ -v /lib/modules:/lib/modules:ro \
258
+ --restart unless-stopped \
259
+ --privileged \
260
+ wireguard-server
261
+
262
+ echo "🚀 WireGuard container started!"
263
+ echo "📝 Check logs: docker logs -f wireguard-server"
264
+ echo "📁 Configs will be in: ./wireguard-config/"
265
+
266
+ ---
267
+
268
+ # Makefile
269
+ .PHONY: build run stop logs clean config
270
+
271
+ build:
272
+ docker build -t wireguard-server .
273
+
274
+ run: build
275
+ mkdir -p wireguard-config
276
+ docker run -d \
277
+ --name wireguard-server \
278
+ --cap-add=NET_ADMIN \
279
+ --cap-add=SYS_MODULE \
280
+ --sysctl net.ipv4.ip_forward=1 \
281
+ --sysctl net.ipv6.conf.all.forwarding=1 \
282
+ -p 51820:51820/udp \
283
+ -v $(PWD)/wireguard-config:/etc/wireguard \
284
+ --restart unless-stopped \
285
+ --privileged \
286
+ wireguard-server
287
+
288
+ stop:
289
+ docker stop wireguard-server || true
290
+ docker rm wireguard-server || true
291
+
292
+ logs:
293
+ docker logs -f wireguard-server
294
+
295
+ clean: stop
296
+ docker rmi wireguard-server || true
297
+ rm -rf wireguard-config
298
+
299
+ config:
300
+ docker exec wireguard-server cat /etc/wireguard/peer1.conf
301
 
302
+ status:
303
+ docker exec wireguard-server wg show