Android SDK development environment Docker image
-
It contains the complete Android SDK enviroment, is able to perform all regular Android jobs.
-
Solves the problem of "It works on my machine, but not on XXX machine".
-
Some tool (e.g. Infer), which has complex dependencies might be in conflict with your local environment. Installing the tool within a Docker container is the easiest and perfect solution.
-
Directly being used as Android CI build enviroment.
Provide only the barebone SDK (the latest official minimal package) gives you the most flexibility in tailoring your own SDK tools for your project. You can maintain an external persistent SDK directory, and mount it to any container. In this way, you don't have to waste time on downloading over and over again, meanwhile, without having any unnecessary package.
Gradle and Kotlin compiler come together with this Docker image merely for the sake of convenience / trial.
It is recommended to always execute a build with the Wrapper to ensure a reliable, controlled and standardized execution of the build. Using the Wrapper looks almost exactly like running the build with a Gradle installation. In case the Gradle distribution is not available on the machine, the Wrapper will download it and store in the local file system. Any subsequent build invocation is going to reuse the existing local distribution as long as the distribution URL in the Gradle properties doesnβt change.
Using the Gradle Wrapper lets you build with a precise Gradle version, in order to eliminate any Gradle version problem.
<your_project>/gradle/wrapper/gradle-wrapper.propertiesspecifies the Gradle version- Gradle will be downloaded and unzipped to
~/.gradle/wrapper/dists/ kotlin-compiler-embeddable-x.y.z.jarwill be resolved and downloaded when executing a Gradle task, it's defined in<your_project>/build.gradleasclasspath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
Previously, running Android SDK update directly within the Dockerfile or inside a container would fail with AUFS storage driver, it was due to hardlink move operations (during updating Android SDK) are not supported by AUFS storage driver, but changing it to other storage driver would work.
What happens if the update fails?
ls $ANDROID_HOME/tools/
#=> empty, nothing is there
# tools such as: android, sdkmanager, emulator, lint and etc. are gone
android
#=> bash: android: command not found
sdkmanager
#=> bash: /opt/android-sdk/tools/bin/sdkmanager: No such file or directoryTo prevent this problem from happening, and you don't wanna bother modifying storage driver. The only solution is to mount an external SDK volume from host to container. Then you are free to try any of below approaches.
-
Update SDK in the usual way but directly inside container.
-
Update SDK from host directory (Remember: the host machine must be the same target architecture as the container -
x86_64 Linux).
If you by accident update SDK on a host machine which has a mismatch target architecture than the container, some binaries won't be executable in container any longer.
gradle <some_task>
#=> Error: java.util.concurrent.ExecutionException: java.lang.RuntimeException: AAPT process not ready to receive commands
$ANDROID_HOME/build-tools/x.x.x/aapt
#=> aapt: cannot execute binary file: Exec format error
adb
#=> adb: cannot execute binary file: Exec format errorNote:
-
-
AUFS storage driver was deprecated in Docker Community Edition 18.06.0-ce-mac70 2018-07-25. And AUFS support was removed in Docker Community Edition 2.0.0.0-mac78 2018-11-19. For more details, please check Docker for Mac Stable release notes.
More information about storage driver:
-
Check Docker's current storage driver option
docker info | grep 'Storage Driver' -
Check which filesystems are supported by the running host kernel
cat /proc/filesystems -
Some storage drivers only work with specific backing filesystems. Check supported backing filesystems for further details.
-
In order to change the storage driver, you need to edit the daemon configuration file, or go to Docker Desktop -> Preferences... -> Daemon -> Advanced.
{ "storage-driver": "" }
# build the image
# set the working directory to the project's root directory first
docker build -t android-sdk android-sdk
# or you can also pass specific tool version as you wish (optional, while there is default version)
docker build --build-arg GRADLE_VERSION=<gradle_version> --build-arg KOTLIN_VERSION=<kotlin_version> --build-arg ANDROID_SDK_VERSION=<android_sdk_version> -t android-sdk android-sdk
# or pull the image instead of building on your own
docker pull minddocdev/android-sdk
# below commands assume that you've pulled the image
# copy the pre-downloaded SDK to the mounted 'sdk' directory
docker run -it --rm -v $(pwd)/sdk:/sdk minddocdev/android-sdk bash -c 'cp -a $ANDROID_HOME/. /sdk'
# go to the 'sdk' directory on the host, update the SDK
# ONLY IF the host machine is the same target architecture as the container
# JDK required on the host
sdk/tools/bin/sdkmanager --update
# or install specific packages
sdk/tools/bin/sdkmanager "build-tools;x.y.z" "platforms;android-x" ...
# mount the updated SDK to container again
# if the host SDK directory is mounted to more than one container
# to avoid multiple containers writing to the SDK directory at the same time
# you should mount the SDK volume in read-only mode
docker run -it -v $(pwd)/sdk:/opt/android-sdk:ro minddocdev/android-sdk /bin/bash
# you can mount without read-only option, only if you need to update SDK inside container
docker run -it -v $(pwd)/sdk:/opt/android-sdk minddocdev/android-sdk /bin/bash
# to keep and reuse Gradle cache
docker run -it -v $(pwd)/sdk:/opt/android-sdk -v $(pwd)/gradle_caches:/root/.gradle/caches minddocdev/android-sdk /bin/bash
# to stop and remove container
# when the image was pulled from a registry
docker stop $(docker ps -aqf "ancestor=minddocdev/android-sdk") &> /dev/null && docker rm $(docker ps -aqf "ancestor=minddocdev/android-sdk") &> /dev/null
# when the image was built locally
docker stop $(docker ps -aqf "ancestor=android-sdk") &> /dev/null && docker rm $(docker ps -aqf "ancestor=android-sdk") &> /dev/null
# more flexible way - doesn't matter where the image comes from
docker stop $(docker ps -a | grep 'android-sdk' | awk '{ print $1 }') &> /dev/null && docker rm $(docker ps -a | grep 'android-sdk' | awk '{ print $1 }') &> /dev/nullA helper script is provided at /opt/license_accepter.sh for accepting the SDK and its various licenses. This is helpful in non-interactive environments such as CI builds.
You can host the Android SDK in one host-independent place, and share it across different containers. One solution is using NFS (Network File System).
To make the container consume the NFS, you can try either way below:
-
Mount the NFS onto your host machine, then run container with volume option (
-v). -
Use a Docker volume plugin, for instance Convoy plugin.
And here are instructions for configuring a NFS server (on Ubuntu):
sudo apt-get update
sudo apt-get install -y nfs-kernel-server
sudo mkdir -p /var/nfs/android-sdk
# put the Android SDK under /var/nfs/android-sdk
# if you haven't got any, run below commands
sudo apt-get install -y wget zip
cd /var/nfs/android-sdk
sudo wget -q $(wget -q -O- 'https://developer.android.com/sdk' | grep -o "\"https://.*android.*tools.*linux.*\"" | sed "s/\"//g")
sudo unzip *tools*linux*.zip
sudo rm *tools*linux*.zip
sudo mkdir licenses
echo 8933bad161af4178b1185d1a37fbf41ea5269c55 | sudo tee licenses/android-sdk-license > /dev/null
echo 84831b9409646a918e30573bab4c9c91346d8abd | sudo tee licenses/android-sdk-preview-license > /dev/null
echo d975f751698a77b662f1254ddbeed3901e976f5a | sudo tee licenses/intel-android-extra-license > /dev/null
# configure and launch NFS service
sudo chown nobody:nogroup /var/nfs
echo "/var/nfs *(rw,sync,no_subtree_check,no_root_squash)" | sudo tee --append /etc/exports > /dev/null
sudo exportfs -a
sudo service nfs-kernel-server startARM emulator is host machine independent, can run anywhere - Linux, macOS, VM and etc. While the performance is a bit poor. On the contrary, x86 emulator requires KVM, which means only runnable on Linux.
According to Google's documentation:
VM acceleration restrictions
Note the following restrictions of VM acceleration:
You can't run a VM-accelerated emulator inside another VM, such as a VM hosted by VirtualBox, VMWare, or Docker. You must run the emulator directly on your system hardware.
You can't run software that uses another virtualization technology at the same time that you run the accelerated emulator. For example, VirtualBox, VMWare, and Docker currently use a different virtualization technology, so you can't run them at the same time as the accelerated emulator.
Read How to Start Intel Hardware-assisted Virtualization (hypervisor) on Linux for more details.
Read KVM Installation if you haven't got KVM installed on the host yet.
-
Check the capability of running KVM
grep -cw ".*\(vmx\|svm\).*" /proc/cpuinfo # or egrep -c '(vmx|svm)' /proc/cpuinfo # a non-zero result means the host CPU supports hardware virtualization. sudo kvm-ok # seeing below info means you can run your virtual machine faster with the KVM extensions INFO: /dev/kvm exists KVM acceleration can be used
-
Load KVM module on the host
modprobe kvm_intel -
Check if KVM module is successfully loaded
lsmod | grep kvm
-
Linux physical machine
-
Cloud computing services (must support nested virtualization)
Note: there will be a performance penalty, primarily for CPU bound workloads and I/O bound workloads.
-
VirtualBox (since 6.0.0, it started supporting nested virtualization, which could be turned on by "Enable Nested VT-x/AMD-V", but at the moment, it's only for AMD CPUs)
-
Check available emulator system images from remote SDK repository
sdkmanager --list --verbose -
Make sure that the required SDK packages are installed, you can find out by above command. To install, use the command below. Whenever you see error complains about
ANDROID_SDK_ROOT, such asPANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOTorPANIC: Broken AVD system path. Check your ANDROID_SDK_ROOT value, it means that you need to install following packages.sdkmanager "platform-tools" "platforms;android-<api_level>" "emulator" -
Download emulator system image(s) (on the host machine)
sdkmanager "system_image_1" "system_image_2" # e.g.: # system-images;android-24;android-tv;x86 # system-images;android-24;default;arm64-v8a # system-images;android-24;default;armeabi-v7a # system-images;android-24;default;x86 # system-images;android-24;default;x86_64 # system-images;android-24;google_apis;arm64-v8a # system-images;android-24;google_apis;armeabi-v7a # system-images;android-24;google_apis;x86 # system-images;android-24;google_apis;x86_64 # system-images;android-24;google_apis_playstore;x86
-
Run Docker container in privileged mode (not necessary for ARM emulator)
# required by KVM docker run -it --privileged -v $(pwd)/sdk:/opt/android-sdk:ro minddocdev/android-sdk /bin/bash
-
Check acceleration ability (not necessary for ARM emulator)
emulator -accel-check # when succeeds accel: 0 KVM (version 12) is installed and usable. accel # when fails (probably due to unprivileged mode) accel: 8 /dev/kvm is not found: VT disabled in BIOS or KVM kernel module not loaded accel
-
Create a new Android Virtual Device
echo "no" | avdmanager create avd -n <name> -k <sdk_id> # e.g.: echo "no" | avdmanager create avd -n test -k "system-images;android-24;default;armeabi-v7a"
-
List existing Android Virtual Devices
avdmanager list avd # ================================================== Available Android Virtual Devices: Name: test Path: /root/.android/avd/test.avd Target: Default Android System Image Based on: Android 7.0 (Nougat) Tag/ABI: default/armeabi-v7a # ================================================== # or emulator -list-avds # 32-bit Linux Android emulator binaries are DEPRECATED # ================================================== test # ==================================================
-
Launch emulator in background
emulator -avd <virtual_device_name> -no-audio -no-boot-anim -no-window -accel on -gpu off & # if the container is not running in privileged mode, you should see below errors: #=> emulator: ERROR: x86_64 emulation currently requires hardware acceleration! #=> Please ensure KVM is properly installed and usable. #=> CPU acceleration status: /dev/kvm is not found: VT disabled in BIOS or KVM kernel module not loaded # or it's running on top of a VM #=> CPU acceleration status: KVM requires a CPU that supports vmx or svm
-
Check the virtual device status
adb devices # ================================================== List of devices attached emulator-5554 offline # "offline" means it's still booting up # ================================================== # ================================================== List of devices attached emulator-5554 device # "device" means it's ready to be used # ==================================================
Now you can for instance run UI tests on the emulator (just remember, the performance is POOR):
<your_android_project>/gradlew connectedAndroidTestIf you encounter an error "Process system isn't responding" in the emulator, like below:
You could try:
-
Increase the limit of the memory resource available to Docker Engine.
-
Increase the amount of physical RAM on the emulator by setting / changing
hw.ramSizein the AVD's configuration file (config.ini). By default, it's not set and the default value is "96" (in megabytes). You could simply set a new value via this command:echo "hw.ramSize=1024" >> /root/.android/avd/<your_avd_name>.avd/config.ini
You can give a container access to host's USB Android devices.
# on Linux
docker run -it --privileged -v /dev/bus/usb:/dev/bus/usb -v $(pwd)/sdk:/opt/android-sdk minddocdev/android-sdk /bin/bash
# or
# try to avoid privileged flag, just add necessary capabilities when possible
# --device option allows you to run devices inside the container without the --privileged flag
docker run -it --device=/dev/ttyUSB0 -v $(pwd)/sdk:/opt/android-sdk minddocdev/android-sdk /bin/bashNote:
-
Connect Android device via USB on host first;
-
Launch container;
-
Disconnect and connect Android device on USB;
-
Select OK for "Allow USB debugging" on Android device;
-
Now the Android device will show up inside the container (
adb devices).
Don't worry about adbkey or adbkey.pub under /.android, not required.
Docker for Mac FAQ says:
Unfortunately it is not possible to pass through a USB device (or a serial port) to a container.
-
Check installed Android SDK tools version
cat $ANDROID_HOME/tools/source.properties | grep Pkg.Revision cat $ANDROID_HOME/platform-tools/source.properties | grep Pkg.Revision
The "
android" command is deprecated. For command-line tools, usetools/bin/sdkmanagerandtools/bin/avdmanager. -
List installed and available packages
sdkmanager --list # print full details instead of truncated path sdkmanager --list --verbose
-
Update all installed packages to the latest version
sdkmanager --update
-
Install packages
The packages argument is an SDK-style path as shown with the
--listcommand, wrapped in quotes (for example,"extras;android;m2repository"). You can pass multiple package paths, separated with a space, but they must each be wrapped in their own set of quotes.sdkmanager "extras;android;m2repository" "extras;google;m2repository" "extras;google;google_play_services" "extras;google;instantapps" "extras;m2repository;com;android;support;constraint;constraint-layout;1.0.2" "build-tools;26.0.0" "platforms;android-26"
-
Stop emulator
adb -s <device_sn> emu kill
Sometimes you may encounter OOM (Out of Memory) issue. The issues vary in logs, while you could find the essence by checking the exit code (echo $?).
For demonstration, below examples try to execute MemoryFiller which can fill memory up quickly.
-
Exit Code
137(= 128 + 9 = SIGKILL = Killed)Example code:
# spin up a container with memory limit (128MB) docker run -it -m 128m -v $(pwd)/misc/MemoryFiller:/root/MemoryFiller thyrlian/android-sdk /bin/bash # fill memory up cd /root/MemoryFiller && javac MemoryFiller.java java MemoryFiller
Logs:
KilledCommentary: The process was in extreme resource starvation, thus was killed by the kernel OOM killer. This happens when JVM max heap size > actual container memory. Similarly, the logs could look like this when running a gradle task in an Android project:
Process 'Gradle Test Executor 1' finished with non-zero exit value 137. -
Exit Code
1(= SIGHUP = Hangup)Example code:
# spin up a container with memory limit (or without - both lead to the same result) docker run -it -m 128m -v $(pwd)/misc/MemoryFiller:/root/MemoryFiller minddocdev/android-sdk /bin/bash # fill memory up # enable Docker memory limits transparency for JVM cd /root/MemoryFiller && javac MemoryFiller.java java -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap MemoryFiller
Logs:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at MemoryFiller.main(MemoryFiller.java:13)Commentary: With enabling Docker memory limits transparency for JVM, JVM is able to correctly estimate the max heap size, and it won't be killed by the kernel OOM killer any more. Similarly, the logs could look like this when running a gradle task in an Android project:
Process 'Gradle Test Executor 1' finished with non-zero exit value 1. In this case, you should either check your code or tweak your memory limit for container (or JVM heap parameters, or even the host memory size). -
Exit Code
3(= SIGQUIT = Quit)Example code:
# spin up a container without memory limit docker run -it -v $(pwd)/misc/MemoryFiller:/root/MemoryFiller minddocdev/android-sdk /bin/bash # fill memory up cd /root/MemoryFiller && javac MemoryFiller.java # make sure that Docker memory resource is big enough > JVM max heap size # otherwise it's better to run with UnlockExperimentalVMOptions & UseCGroupMemoryLimitForHeap enabled java -XX:+ExitOnOutOfMemoryError MemoryFiller
Logs:
Terminating due to java.lang.OutOfMemoryError: Java heap spaceCommentary: JRockit JVM exits on the first occurrence of an OOM error. It can be used if you prefer restarting an instance of JRockit JVM rather than handling OOM errors.
-
Exit Code
134(= 128 + 6 = SIGABRT = Abort)Example code:
# spin up a container without memory limit docker run -it -v $(pwd)/misc/MemoryFiller:/root/MemoryFiller minddocdev/android-sdk /bin/bash # fill memory up cd /root/MemoryFiller && javac MemoryFiller.java # make sure that Docker memory resource is big enough > JVM max heap size # otherwise it's better to run with UnlockExperimentalVMOptions & UseCGroupMemoryLimitForHeap enabled java -XX:+CrashOnOutOfMemoryError MemoryFiller
Logs:
Aborting due to java.lang.OutOfMemoryError: Java heap space # # A fatal error has been detected by the Java Runtime Environment: # # Internal Error (debug.cpp:308), pid=63, tid=0x00007f208708d700 # fatal error: OutOfMemory encountered: Java heap space # # JRE version: OpenJDK Runtime Environment (8.0_131-b11) (build 1.8.0_131-8u131-b11-2ubuntu1.16.04.3-b11) # Java VM: OpenJDK 64-Bit Server VM (25.131-b11 mixed mode linux-amd64 compressed oops) # Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again # # An error report file with more information is saved as: # /root/MemoryFiller/hs_err_pid63.log # # If you would like to submit a bug report, please visit: # http://bugreport.java.com/bugreport/crash.jsp # Aborted
Commentary: JRockit JVM crashes and produces text and binary crash files when an OOM error occurs. When JVM crashes with a fatal error, an error report file
hs_err_pid***.logwill be generated in the same working directory.
-
JVM is not container aware, and always guesses about the memory resource (for JDK version earlier than 8u131 or 9).
-
Many tools (such as
free,vmstat,top) were invented before the existence of cgroups, thus they have no clue about the resources limits. -
-XX:MaxRAMFraction: maximum fraction (1/n) of real memory used for maximum heap size (-XX:MaxHeapSize/-Xmx), the default value is 4. -
-XX:MaxMetaspaceSize: where class metadata reside.-XX:MaxPermSizeis deprecated in JDK 8. It used to be Permanent Generation space before JDK 8, which could causejava.lang.OutOfMemoryError: PermGenproblem. -
-XshowSettings:category: shows settings and continues. Possible category arguments for this option include the following:all(all categories of settings, the default value),locale(settings related to locale),properties(settings related to system properties),vm(settings of the JVM). To get JVM Max Heap Size, simply runjava -XshowSettings:vm -version -
-XX:+PrintFlagsFinal: print all VM flags after argument and ergonomic processing. You can runjava -XX:+PrintFlagsFinal -versionto get all information. -
By default, Android Gradle Plugin sets the maxProcessCount to 4 (the maximum number of concurrent processes that can be used to dex).
Total Memory = maxProcessCount * javaMaxHeapSize -
Set the environment variable
_JAVA_OPTIONSto-XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap. Then you'll see such logs likePicked up _JAVA_OPTIONS: -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeapduring any task execution, which means it takes effect. -
JDK 10 has introduced
-XX:+UseContainerSupportwhich is enabled by defaul to improve the execution and configurability of Java running in Docker containers. -
JAVA_OPTSenvironment variable won't be used by JVM directly, but sometimes get recognized by other apps (e.g. Apache Tomcat) as configuration. If you want to use it for any Java executable, do it like this:java $JAVA_OPTS ... -
The official
JAVA_TOOL_OPTIONSenvironment variable is provided to augment a command line, so that command line options can be passed without accessing or modifying the launch command. It is recognized by all VMs. -
You can tweak
-Xmsor-Xmxon your own to specify the initial or maximum heap size.
# on macOS
brew install socat
socat TCP-LISTEN:2376,reuseaddr,fork UNIX-CONNECT:/var/run/docker.sock
#====================================================================================================#
# on Linux (Debian / Ubuntu)
# changing DOCKER_OPTS is optional
# Use DOCKER_OPTS to modify the daemon startup options
# echo -e '\nDOCKER_OPTS="-H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock"\n' | sudo tee --append /etc/default/docker > /dev/null
# find the location of systemd unit file
systemctl status docker
#=> docker.service - Docker Application Container Engine
#=> Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
sudo sed -i.bak 's?ExecStart.*?ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2376 -H unix:///var/run/docker.sock?g' /lib/systemd/system/docker.service
sudo systemctl daemon-reload
sudo systemctl restart docker.service
# check if the port is listened or not
sudo netstat -tulpn | grep LISTENRelease is published from master automatically with Github actions.
This is a fork from thyrlian/AndroidSDK and its LICENSE applies.
Copyright (c) 2016-2019 Jing Li. It is released under the Apache License. See the LICENSE file for details.
By continuing to use this Docker Image, you accept the terms in below license agreement.
