Сборка Android-проекта в Docker-контейнере
Разрабатывая проект под платформу Android, даже самый небольшой, рано или поздно приходится сталкиваться с окружением для разработки. Кроме Android SDK, необходимо чтобы была последняя версия Kotlin, Gradle, platform-tools, build-tools. И если на машине разработчика все эти зависимости решаются в большей мере с помощью Android Studio IDE, то на сервере CI/CD каждое обновление может превратиться в головную боль. И если в web-разработке, решением проблемы окружения стандартом стал Docker, то почему-бы не попробовать решить с помощью него аналогичную проблему и в Android-разработке…
Для тех, кто не знает что такое Docker — если совсем просто, то это инструмент создания т.н. «контейнеров» где содержится минимальное ядро ОС и необходимый набор ПО, которые мы можем разворачивать где захотим, сохраняя при этом окружение. Что именно будет в нашем контейнере определяется в Dockerfile, который потом собирается в образ запускаемый где угодно и обладающий свойства идемпотентности.
Процесс установки и основы Docker прекрасно описаны на его официальном сайте. Поэтому, забегая немного вперед, вот такой Dockerfile у нас получился
Сохраняем его в папку с нашим Android-проектом и запускаем сборку контейнера командой
Параметр -t задает tag или имя нашего контейнера, которое обычно состоит из его название и версии. В нашем случае мы назвали его android-build а в версии указали совокупность версий gradle, android-sdk и platform-tools. В дальнейшем нам проще будет искать нужный нам образ по имени используя такую «версию».
После того как сборка прошла мы можем использовать наш образ локально, можем загрузить его командой docker push в публичный или приватный репозиторий образов чтобы скачивать его на другие машины.
В качестве примера соберем локально проект. Для этого в папке с проектом выполним команду
Разберем что она означает:
docker run — сама команда запуска образа
-rm — означает что после остановки контейнера он удаляет за собой все что создавалось в процессе его жизни
-v «$PWD»:/home/gradle/ — монтирует текущую папку с нашим Android-проектом во внутреннюю папку контейнера /home/gradle/
-w /home/gradle — задает рабочую директорию контейнера
android-build:5.4.1-28-27 — имя нашего контейнера, который мы собрали
gradle assembleDebug — собственно команда сборки, которая собирает наш проект
Если все сложиться удачно, то через пару секунд/минут вы увидите у себя на экране что-то вроде BUILD SUCCESSFUL in 8m 3s! А в папке app/build/output/apk будет лежать собранное приложение.
Аналогичным образом можно выполнять другие задачи gradle — проверять проект, запускать тесты и т.д. Основное преимущество — при необходимости сборки проекта на любой другой машине, нам не нужно беспокоиться об установке всего окружения и достаточно будет скачать необходимый образ и запустить в нем сборку.
Контейнер не хранит никаких изменений, и каждая сборка запускается с нуля, что с одной стороны гарантирует идентичность сборки независимо от места ее запуска, с другой стороны каждый раз приходиться скачивать все зависимости и компилировать весь код заново, а это иногда может занимать существенное время. Поэтому кроме обычного «холодного» запуска у нас есть вариант запуска сборки с сохранением т.н. «кэша», где мы сохраняем папку
/.gradle просто копируя ее в рабочую папку проекта, а в начале следующей сборки возвращаем ее обратно. Все процедуры копирования мы вынесли в отдельные скрипты и сама команда запуска у нас стала выглядеть так
В итоге, среднее время сборки проекта у нас сократилось в несколько раз (в зависимости от числа зависимостей на проекте, но средний проект таким образом стал собираться за 1 минуту вместо 5 минут).
Все это само собой имеет смысл только если у вас есть собственный внутренний CI/CD сервер, поддержкой которого вы сами и занимаетесь. Но сейчас есть много облачных сервисов в которых все эти проблемы решены и вам не надо об этом переживать и нужные свойства сборки можно так же указать в настройках проекта.
Источник
Docker android app apk
Docker Android Build Box
An optimized Docker image that includes the Android SDK and Flutter SDK.
It includes the following components:
- Ubuntu 20.04
- Java (OpenJDK)
- 1.8
- 11
- Android SDKs for platforms:
- 26
- 27
- 28
- 29
- 30
- 31
- Android build tools:
- 26.0.0 26.0.1 26.0.2
- 27.0.1 27.0.2 27.0.3
- 28.0.1 28.0.2 28.0.3
- 29.0.2 29.0.3
- 30.0.0 30.0.2 30.0.3
- 31.0.0
- Android NDK (always the latest version, side-by-side install)
- Android Emulator
- TestNG
- Python 3.8.10
- Node.js 14, npm, React Native
- Ruby, RubyGems
- fastlane
- Flutter 2.5.1
- jenv
Pull Docker Image
The docker image is a publicly automated build on Docker Hub based on the Dockerfile in this repo, so there is no hidden stuff in it. To pull the latest docker image:
Hint: You can use a tag to a specific stable version, rather than latest of docker image, to avoid breaking your build. e.g. mingc/android-build-box:1.22.0 . Take a look at the Tags section, at the bottom of this page, to see all the available tags.
Use the image to build an Android project
You can use this docker image to build your Android project with a single docker command:
To build .aab bundle release, use ./gradlew bundleRelease :
Run docker image with interactive bash shell:
Add the following arguments to the docker command to cache the home gradle folder:
Build an Android project with Bitbucket Pipelines
If you have an Android project in a Bitbucket repository and want to use the pipeline feature to build it, you can simply specify this docker image. Here is an example of bitbucket-pipelines.yml :
The caches are used to store downloaded dependencies from previous builds, to speed up the next builds.
Build a Flutter project with Github Actions
Here is an example .github/workflows/main.yml to build a Flutter project with this docker image:
Run an Android emulator in the Docker build machine
Using guidelines from.
. You can write a script to create and launch an ARM emulator, which can be used for running integration tests or instrumentation tests or unit tests:
Note that x86_64 emulators are not currently supported. See Issue #18 for details.
Choose the system Java version
Both Java 1.8 and Java 11 are installed. As of version 1.20, jenv can be used to switch between different versions of Java.
docker-android-build-box version | Date released | Java version available |
---|---|---|
1.19 and below | 2 July 2020 and earlier | Java 8 installed only |
1.20 — 1.23 | 7 August 2020 — 23 Sept 2021 | Both Java 8 and Java 11 installed. The default is Java 8. |
1.23.1 | 28 September 2021 | Both Java 8 and Java 11 installed. The default is Java 11. |
The following example sets Java to version 8:
Build the Docker Image
If you want to build the docker image by yourself, you can use following command. The image itself is around 5 GB, so check your free disk space before building it.
You can use a tag to a specific stable version, rather than latest of docker image, to avoid breaking your build. For example mingc/android-build-box:1.22.0
Note: versions 1.0.0 up to 1.17.0 included every single Build Tool version and every Android Platform version available. This generated large Docker images, around 5 GB. Newer versions of android-build-box only include a subset of the newest Android Tools, so the Docker images are smaller.
- PR #76: Tidy up to reduce image size @ozmium
- Remove JDK 16, Android build not support JDK 16 yet.
NOTE: missed this tag in DockerHub due to a github action error, should use 1.23.1 instead.
Источник
Docker android app apk
Android in docker solution with noVNC supported and video recording
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Docker-Android is a docker image built to be used for everything related to mobile website testing and Android project.
Emulator — Samsung Device | Emulator — Nexus Device | Real Device |
---|---|---|
- Run UI tests for mobile websites with appium
- Build Android project and run unit tests with the latest build-tools
- Run UI tests for Android applications with different frameworks (appium, espresso, robotium, etc.)
- Run monkey / stress tests
- SMS testing
Advantages compare with other docker-android projects
- noVNC to see what happen inside docker container
- Emulator for different devices / skins, such as Samsung Galaxy S6, LG Nexus 4, HTC Nexus One and more.
- Ability to connect to Selenium Grid
- Ability to control emulator from outside container by using adb connect
- Support real devices with screen mirroring
- Ability to record video during test execution for debugging
- Integrated with other cloud solutions, e.g. Genymotion Cloud
- Open source with more features coming
List of Docker images
OS | Android | API | Browser | Browser version | Chromedriver | Image | Size |
---|---|---|---|---|---|---|---|
Linux | 6.0 | 23 | browser | 44.0 | 2.18 | budtmo/docker-android-x86-6.0 | |
Linux | 7.0 | 24 | chrome | 51.0 | 2.23 | budtmo/docker-android-x86-7.0 | |
Linux | 7.1.1 | 25 | chrome | 55.0 | 2.28 | budtmo/docker-android-x86-7.1.1 | |
Linux | 8.0 | 26 | chrome | 58.0 | 2.31 | budtmo/docker-android-x86-8.0 | |
Linux | 8.1 | 27 | chrome | 61.0 | 2.33 | budtmo/docker-android-x86-8.1 | |
Linux | 9.0 | 28 | chrome | 66.0 | 2.40 | budtmo/docker-android-x86-9.0 | |
Linux | 10.0 | 29 | chrome | 74.0 | 74.0.3729.6 | budtmo/docker-android-x86-10.0 | |
Linux | 11.0 | 30 | chrome | 83.0 | 83.0.4103.39 | budtmo/docker-android-x86-11.0 | |
Linux | 12.0 | 31 | chrome | 93.0 | 93.0.4577.15 | budtmo/docker-android-x86-12.0 | |
All | — | — | — | — | — | budtmo/docker-android-real-device | |
All | All | All | All | All | All | budtmo/docker-android-genymotion |
List of Devices
Type | Device Name |
---|---|
Phone | Samsung Galaxy S10 |
Phone | Samsung Galaxy S9 |
Phone | Samsung Galaxy S8 |
Phone | Samsung Galaxy S7 Edge |
Phone | Samsung Galaxy S7 |
Phone | Samsung Galaxy S6 |
Phone | Nexus 4 |
Phone | Nexus 5 |
Phone | Nexus One |
Phone | Nexus S |
Tablet | Nexus 7 |
Docker is installed in your system.
Your machine need to support virtualization. To check it:
For Linux OS, please use image name that contains «x86»
For OSX and Windows OS, please use Virtual Machine that support Virtualization with Ubuntu OS
Verify the ip address of docker host.
For OSX, you can find out by using following command:
For different OS, localhost should work.
Open http://docker-host-ip-address:6080 from web browser. Note: Adding ?view_only=true will give user only view only permission.
This document contains custom configurations of Docker-Android that you might need, e.g. Proxy, Changing language on fly, etc.
Build Android project
Docker-Android can be used for building Android project and executing its unit test. This following steps will illustrate how to build Android project:
Build the project
Control Android connected to host (Emulator or Real Device)
Create a docker container with this command
Open terminal by clicking right on noVNC window >> Terminal emulator
To connect to host’s adb (make sure your host have adb and connected to the device.)
To specify port, just add -P port_number
Now your container can access your host devices. But, you need to add remoteAdbHost and adbPort desired capabilities to make Appium can recognise those devices.
Appium and Selenium Grid
If you want to use Appium and Selenium Grid, you can follow this document. It also contains sample and use cases.
Control android emulator outside container
Note: You need to have Android Debug Bridge (adb) installed in your host machine.
- Find the auth_token and copy it.
- Access emulator using telnet and login with auth_token
- Login with given auth_token from 1.step
You can also integrate it inside project using adb library.
Google Play Services and Google Play Store
Not installed at this time.
This document gives you information about custom plugin that supports Docker-Android.
This document shows you how to configure Virtual Machine on VMWARE to be able to run Docker-Android.
This document contains information about deploying Docker-Android on cloud services.
For you who do not have ressources to maintain the simulator or to buy machines or need different device profiles, you need to give a try to Genymotion Cloud. Docker-Android is integrated with Genymotion on different cloud services, e.g. Genymotion Cloud, AWS, GCP, Alibaba Cloud. Please follow this document or this blog for more detail.
All logs inside container are stored under folder /var/log/supervisor. you can print out log file by using docker exec. Example:
All docker images are protected by Polyverse by scrambling the Linux packages. For more information please visit this link
You can use cadvisor combined with influxdb / prometheus and grafana if needed to monitor each running container.
Docker-Android are being used by 100+ countries around the world.
Источник