0
# Container Operations
1
2
Container operations provide direct interaction with individual containers within container groups, including log retrieval, command execution, and container attachment.
3
4
## Log Operations
5
6
### List Container Logs { .api }
7
8
```python
9
def list_logs(
10
resource_group_name: str,
11
container_group_name: str,
12
container_name: str,
13
**kwargs
14
) -> Logs:
15
"""
16
Retrieve logs from a specific container.
17
18
Args:
19
resource_group_name (str): Name of the resource group
20
container_group_name (str): Name of the container group
21
container_name (str): Name of the container
22
tail (int, optional): Number of lines to tail from the end of the logs
23
timestamps (bool, optional): Include timestamps in the log output
24
25
Returns:
26
Logs: Container logs with content property containing log text
27
28
Example:
29
# Get all logs
30
logs = client.containers.list_logs(
31
resource_group_name="my-resource-group",
32
container_group_name="my-container-group",
33
container_name="web-server"
34
)
35
print(logs.content)
36
37
# Get last 100 lines with timestamps
38
recent_logs = client.containers.list_logs(
39
resource_group_name="my-resource-group",
40
container_group_name="my-container-group",
41
container_name="web-server",
42
tail=100,
43
timestamps=True
44
)
45
print(recent_logs.content)
46
"""
47
```
48
49
## Command Execution
50
51
### Execute Command in Container { .api }
52
53
```python
54
def execute_command(
55
resource_group_name: str,
56
container_group_name: str,
57
container_name: str,
58
container_exec_request: ContainerExecRequest,
59
**kwargs
60
) -> ContainerExecResponse:
61
"""
62
Execute a command inside a running container.
63
64
Args:
65
resource_group_name (str): Name of the resource group
66
container_group_name (str): Name of the container group
67
container_name (str): Name of the container
68
container_exec_request (ContainerExecRequest): Command execution request
69
70
Returns:
71
ContainerExecResponse: Response containing WebSocket URI and password for command execution
72
73
Example:
74
from azure.mgmt.containerinstance.models import (
75
ContainerExecRequest, ContainerExecRequestTerminalSize
76
)
77
78
# Execute a simple command
79
exec_request = ContainerExecRequest(
80
command=["ls", "-la", "/app"]
81
)
82
83
exec_response = client.containers.execute_command(
84
resource_group_name="my-resource-group",
85
container_group_name="my-container-group",
86
container_name="web-server",
87
container_exec_request=exec_request
88
)
89
90
print(f"WebSocket URI: {exec_response.web_socket_uri}")
91
92
# Execute interactive bash with terminal size
93
interactive_request = ContainerExecRequest(
94
command=["/bin/bash"],
95
terminal_size=ContainerExecRequestTerminalSize(rows=24, cols=80)
96
)
97
98
interactive_response = client.containers.execute_command(
99
resource_group_name="my-resource-group",
100
container_group_name="my-container-group",
101
container_name="web-server",
102
container_exec_request=interactive_request
103
)
104
"""
105
```
106
107
## Container Attachment
108
109
### Attach to Container { .api }
110
111
```python
112
def attach(
113
resource_group_name: str,
114
container_group_name: str,
115
container_name: str,
116
**kwargs
117
) -> ContainerAttachResponse:
118
"""
119
Attach to a container's main process for interactive access.
120
121
Args:
122
resource_group_name (str): Name of the resource group
123
container_group_name (str): Name of the container group
124
container_name (str): Name of the container
125
126
Returns:
127
ContainerAttachResponse: Response containing WebSocket URI and password for attachment
128
129
Example:
130
# Attach to container
131
attach_response = client.containers.attach(
132
resource_group_name="my-resource-group",
133
container_group_name="my-container-group",
134
container_name="interactive-container"
135
)
136
137
print(f"Attach WebSocket URI: {attach_response.web_socket_uri}")
138
# Use the WebSocket URI to establish connection for interactive access
139
"""
140
```
141
142
## Usage Examples
143
144
### Log Monitoring and Debugging
145
146
```python
147
import time
148
from azure.mgmt.containerinstance.models import ContainerExecRequest
149
150
def monitor_container_health(client, resource_group, container_group, container_name):
151
"""Monitor container health through logs and commands."""
152
153
# Check recent logs for errors
154
logs = client.containers.list_logs(
155
resource_group_name=resource_group,
156
container_group_name=container_group,
157
container_name=container_name,
158
tail=50,
159
timestamps=True
160
)
161
162
if "ERROR" in logs.content or "FAILED" in logs.content:
163
print("Errors detected in logs:")
164
print(logs.content)
165
166
# Execute health check command
167
health_check = ContainerExecRequest(
168
command=["curl", "-f", "http://localhost:8080/health"]
169
)
170
171
health_response = client.containers.execute_command(
172
resource_group_name=resource_group,
173
container_group_name=container_group,
174
container_name=container_name,
175
container_exec_request=health_check
176
)
177
178
# Process health check response through WebSocket connection
179
print(f"Health check WebSocket: {health_response.web_socket_uri}")
180
181
# Usage
182
monitor_container_health(
183
client=client,
184
resource_group="production-rg",
185
container_group="web-app-cg",
186
container_name="web-server"
187
)
188
```
189
190
### Database Migration Script Execution
191
192
```python
193
def run_database_migration(client, resource_group, container_group, container_name):
194
"""Execute database migration scripts in a container."""
195
196
# Run migration command
197
migration_request = ContainerExecRequest(
198
command=["python", "/app/manage.py", "migrate", "--database=production"]
199
)
200
201
migration_response = client.containers.execute_command(
202
resource_group_name=resource_group,
203
container_group_name=container_group,
204
container_name=container_name,
205
container_exec_request=migration_request
206
)
207
208
print(f"Migration started. WebSocket URI: {migration_response.web_socket_uri}")
209
210
# Wait and check logs for migration results
211
time.sleep(30)
212
213
migration_logs = client.containers.list_logs(
214
resource_group_name=resource_group,
215
container_group_name=container_group,
216
container_name=container_name,
217
tail=20
218
)
219
220
if "Migration completed successfully" in migration_logs.content:
221
print("Database migration completed successfully")
222
else:
223
print("Migration may have failed. Check logs:")
224
print(migration_logs.content)
225
226
# Usage
227
run_database_migration(
228
client=client,
229
resource_group="production-rg",
230
container_group="backend-cg",
231
container_name="api-server"
232
)
233
```
234
235
### Interactive Debugging Session
236
237
```python
238
def start_debug_session(client, resource_group, container_group, container_name):
239
"""Start an interactive debugging session in a container."""
240
241
from azure.mgmt.containerinstance.models import ContainerExecRequestTerminalSize
242
243
# Start interactive bash session
244
debug_request = ContainerExecRequest(
245
command=["/bin/bash"],
246
terminal_size=ContainerExecRequestTerminalSize(rows=30, cols=120)
247
)
248
249
debug_response = client.containers.execute_command(
250
resource_group_name=resource_group,
251
container_group_name=container_group,
252
container_name=container_name,
253
container_exec_request=debug_request
254
)
255
256
print("Debug session started!")
257
print(f"WebSocket URI: {debug_response.web_socket_uri}")
258
print(f"Password: {debug_response.password}")
259
print("Use a WebSocket client to connect and start debugging")
260
261
return debug_response
262
263
# Usage
264
debug_session = start_debug_session(
265
client=client,
266
resource_group="development-rg",
267
container_group="test-app-cg",
268
container_name="debug-container"
269
)
270
```
271
272
## WebSocket Connection Handling
273
274
The `execute_command` and `attach` operations return WebSocket connection details that require additional handling:
275
276
```python
277
import websocket
278
import json
279
280
def connect_to_container_websocket(websocket_uri, password):
281
"""Example WebSocket connection handler for container operations."""
282
283
def on_message(ws, message):
284
print(f"Container output: {message}")
285
286
def on_error(ws, error):
287
print(f"WebSocket error: {error}")
288
289
def on_close(ws, close_status_code, close_msg):
290
print("WebSocket connection closed")
291
292
def on_open(ws):
293
print("WebSocket connection established")
294
# Send authentication if required
295
auth_message = {"password": password}
296
ws.send(json.dumps(auth_message))
297
298
# Create WebSocket connection
299
ws = websocket.WebSocketApp(
300
websocket_uri,
301
on_open=on_open,
302
on_message=on_message,
303
on_error=on_error,
304
on_close=on_close
305
)
306
307
# Start connection
308
ws.run_forever()
309
310
# Example usage with command execution
311
exec_response = client.containers.execute_command(
312
resource_group_name="my-rg",
313
container_group_name="my-cg",
314
container_name="my-container",
315
container_exec_request=ContainerExecRequest(command=["echo", "Hello World"])
316
)
317
318
# Connect to WebSocket to see command output
319
connect_to_container_websocket(
320
exec_response.web_socket_uri,
321
exec_response.password
322
)
323
```